package cmd

import (
	"fmt"
	"os"
	"path/filepath"

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

var configCmd = &cobra.Command{
	Use:   "config",
	Short: "Manage KeyHunter configuration",
}

var configInitCmd = &cobra.Command{
	Use:   "init",
	Short: "Create default configuration file at ~/.keyhunter.yaml",
	RunE: func(cmd *cobra.Command, args []string) error {
		home, err := os.UserHomeDir()
		if err != nil {
			return fmt.Errorf("cannot determine home directory: %w", err)
		}
		configPath := filepath.Join(home, ".keyhunter.yaml")

		// Set defaults before writing
		viper.SetDefault("scan.workers", 0)
		viper.SetDefault("database.path", filepath.Join(home, ".keyhunter", "keyhunter.db"))

		if err := viper.WriteConfigAs(configPath); err != nil {
			return fmt.Errorf("writing config: %w", err)
		}
		fmt.Printf("Config initialized: %s\n", configPath)
		return nil
	},
}

var configSetCmd = &cobra.Command{
	Use:   "set <key> <value>",
	Short: "Set a configuration value",
	Args:  cobra.ExactArgs(2),
	RunE: func(cmd *cobra.Command, args []string) error {
		key, value := args[0], args[1]
		viper.Set(key, value)
		if err := viper.WriteConfig(); err != nil {
			// If config file doesn't exist yet, create it
			home, _ := os.UserHomeDir()
			configPath := filepath.Join(home, ".keyhunter.yaml")
			if err2 := viper.WriteConfigAs(configPath); err2 != nil {
				return fmt.Errorf("writing config: %w", err2)
			}
		}
		fmt.Printf("Set %s = %s\n", key, value)
		return nil
	},
}

var configGetCmd = &cobra.Command{
	Use:   "get <key>",
	Short: "Get a configuration value",
	Args:  cobra.ExactArgs(1),
	RunE: func(cmd *cobra.Command, args []string) error {
		val := viper.Get(args[0])
		if val == nil {
			return fmt.Errorf("key %q not found", args[0])
		}
		fmt.Printf("%v\n", val)
		return nil
	},
}

func init() {
	configCmd.AddCommand(configInitCmd)
	configCmd.AddCommand(configSetCmd)
	configCmd.AddCommand(configGetCmd)
}
