package main

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"
)

var (
	cfgFile   string
	serverURL string
	cliConfig *CLIConfig
)

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

var rootCmd = &cobra.Command{
	Use:   "whatshook-cli",
	Short: "WhatsHooked CLI - Manage WhatsApp webhooks",
	Long:  `A command-line interface for managing WhatsHooked server, hooks, and WhatsApp accounts.`,
	PersistentPreRun: func(cmd *cobra.Command, args []string) {
		if shouldSkipConfigLoad(cmd) {
			return
		}

		var err error
		cliConfig, err = LoadCLIConfig(cfgFile, serverURL)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error loading config: %v\n", err)
			os.Exit(1)
		}
	},
}

func init() {
	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default: $HOME/.whatshooked/cli.json)")
	rootCmd.PersistentFlags().StringVar(&serverURL, "server", "", "server URL (default: http://localhost:8825)")

	// Add all command groups
	rootCmd.AddCommand(healthCmd)
	rootCmd.AddCommand(hooksCmd)
	rootCmd.AddCommand(accountsCmd)
	rootCmd.AddCommand(sendCmd)
	rootCmd.AddCommand(usersCmd)
	rootCmd.AddCommand(passwordHashCmd)
}

func shouldSkipConfigLoad(cmd *cobra.Command) bool {
	for c := cmd; c != nil; c = c.Parent() {
		if c.Annotations != nil && c.Annotations["skip-config-load"] == "true" {
			return true
		}
	}
	return false
}
