package cmd

import (
	"fmt"
	"os"
	"strings"

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

var (
	cfgFile string

	rootCmd = &cobra.Command{
		Use:   "goblin-store",
		Short: "A fast, concurrent backup utility",
		Long:  `A multi-threaded incremental backup CLI supporting cloud and local targets.`,
	}
)

func Execute() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

func init() {
	cobra.OnInitialize(initConfig)

	// Global flags available across all commands
	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is ~/.config/goblin-store.yaml)")
	rootCmd.PersistentFlags().BoolP("verbose", "v", false, "enable verbose output")

	_ = viper.BindPFlag("verbose", rootCmd.PersistentFlags().Lookup("verbose"))
}

func initConfig() {
	if cfgFile != "" {
		// Explicit config file passed via --config flag
		viper.SetConfigFile(cfgFile)
	} else {
		// 1. Check OS user config directory (~/.config on Linux)
		if configDir, err := os.UserConfigDir(); err == nil {
			viper.AddConfigPath(configDir) // Searches ~/.config/goblin-store.yaml
		}

		// 2. Check current working directory as fallback
		viper.AddConfigPath(".")

		// File base name (without extension) and format
		viper.SetConfigName("goblin-store")
		viper.SetConfigType("yaml")
	}

	viper.SetEnvPrefix("GSBACKUP")
	viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_", ".", "_"))
	viper.AutomaticEnv()

	if err := viper.ReadInConfig(); err == nil {
		if viper.GetBool("verbose") {
			fmt.Printf("Using config file: %s\n", viper.ConfigFileUsed())
		}
	}
}
