package main

import (
	"os"
	"path/filepath"

	"github.com/spf13/viper"
)

// CLIConfig holds the CLI configuration
type CLIConfig struct {
	ServerURL string
	AuthKey   string
	Username  string
	Password  string
}

// LoadCLIConfig loads configuration with priority: config file → ENV → flag
func LoadCLIConfig(configFile string, serverFlag string) (*CLIConfig, error) {
	v := viper.New()

	// Set defaults
	v.SetDefault("server_url", "http://localhost:8825")
	v.SetDefault("auth_key", "")
	v.SetDefault("username", "")
	v.SetDefault("password", "")

	// 1. Load from config file (lowest priority)
	if configFile != "" {
		v.SetConfigFile(configFile)
	} else {
		// Look for config in home directory
		home, err := os.UserHomeDir()
		if err == nil {
			v.AddConfigPath(filepath.Join(home, ".whatshooked"))
			v.SetConfigName("cli")
			v.SetConfigType("json")
		}
		// Also look in current directory
		v.AddConfigPath(".")
		v.SetConfigName(".whatshooked-cli")
		v.SetConfigType("json")
	}

	// Read config file if it exists (don't error if it doesn't)
	_ = v.ReadInConfig()

	// 2. Override with environment variables (medium priority)
	v.SetEnvPrefix("WHATSHOOKED")
	v.AutomaticEnv()

	// 3. Override with command-line flag (highest priority)
	if serverFlag != "" {
		v.Set("server_url", serverFlag)
	}

	cfg := &CLIConfig{
		ServerURL: v.GetString("server_url"),
		AuthKey:   v.GetString("auth_key"),
		Username:  v.GetString("username"),
		Password:  v.GetString("password"),
	}

	return cfg, nil
}
