package cmd

import (
	"fmt"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var configureCmd = &cobra.Command{
	Use:     "configure",
	Short:   "Configure Log credentials(ak,sk,endpoint,regionId) save to config.yaml",
	Example: "ctlts configure <--ak> <--sk> [<--endpoint> <--region_id> <--region_name>]",
	Run: func(cmd *cobra.Command, args []string) {
		ak, _ := cmd.Flags().GetString("ak")
		sk, _ := cmd.Flags().GetString("sk")
		endpoint, _ := cmd.Flags().GetString("endpoint")
		region_name, _ := cmd.Flags().GetString("region_name")
		region_id, _ := cmd.Flags().GetString("region_id")

		// 保存配置
		viper.Set(fmt.Sprintf("config.%s.ak", region_name), ak)
		viper.Set(fmt.Sprintf("config.%s.sk", region_name), sk)
		viper.Set(fmt.Sprintf("config.%s.endpoint", region_name), endpoint)
		viper.Set(fmt.Sprintf("config.%s.region_id", region_name), region_id)

		// 保存到配置文件
		if err := viper.WriteConfig(); err != nil {
			fmt.Println("Error saving configuration:", err)
			return
		}

		fmt.Println("Configuration saved successfully!,See config.yaml")
	},
}

func init() {
	rootCmd.AddCommand(configureCmd)

	configureCmd.Flags().StringP("ak", "a", "", "access_id")
	configureCmd.Flags().StringP("sk", "s", "", "access_key")
	configureCmd.Flags().StringP("endpoint", "e", "https://ctlts-global.ctapi.ctyun.cn", "endpoint")
	configureCmd.Flags().StringP("region_id", "i", "bb9fdb42056f11eda1610242ac110002", "region_id")
	configureCmd.Flags().StringP("region_name", "n", "huadong1", "region_name")
	configureCmd.MarkFlagRequired("ak")
	configureCmd.MarkFlagRequired("sk")
}
