package cmd

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	_ "github.com/yourorg/devour/internal/scraper/external"
	"github.com/yourorg/devour/internal/ui"
)

var (
	cfgFile  string
	verbose  bool
	showLogo bool
)

var rootCmd = &cobra.Command{
	Use:   "devour",
	Short: "Context ingestion and management for AI",
	Long: `      ___
   .-'   '-.
  /  O   O  \
 |     _     |
  \   '-'   /
   '-.___.-'
   Documentation Devourer

Devour scrapes, indexes, and serves documentation from multiple sources
(GitHub repos, OpenAPI specs, web docs, local files) to feed structured
context to AI models for generating accurate, fully working code.

Runs in two modes:
  - Local mode: OpenCode skill running entirely on your machine
  - Remote mode: MCP server for multi-user/team access`,
	Version:      "1.0.0",
	SilenceUsage: true,
}

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

func init() {
	cobra.OnInitialize(initConfig)

	rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "config file (default is ./devour.yaml)")
	rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "enable verbose logging")
	rootCmd.PersistentFlags().BoolVarP(&showLogo, "logo", "l", false, "show the Devour character logo")

	rootCmd.AddCommand(initCmd)
	rootCmd.AddCommand(scrapeCmd)
	rootCmd.AddCommand(getCmd)
	rootCmd.AddCommand(askCmd)
	rootCmd.AddCommand(languagesCmd)
	rootCmd.AddCommand(demoCmd)
	rootCmd.AddCommand(serveCmd)
	rootCmd.AddCommand(queryCmd)
	rootCmd.AddCommand(statusCmd)
	rootCmd.AddCommand(syncCmd)
	rootCmd.AddCommand(pushCmd)
	rootCmd.AddCommand(logoCmd)
	rootCmd.AddCommand(scorecardCmd)
	rootCmd.AddCommand(autoCmd)
	rootCmd.AddCommand(verifyCmd)
}

// logoCmd displays the Devour character
var logoCmd = &cobra.Command{
	Use:   "logo",
	Short: "Display the Devour character logo",
	Long:  `Display the ASCII art Devour character mascot.`,
	Run: func(cmd *cobra.Command, args []string) {
		ui.PrintCharacter()
	},
}

func initConfig() {
	if cfgFile != "" {
		viper.SetConfigFile(cfgFile)
	} else {
		viper.AddConfigPath(".")
		viper.AddConfigPath("$HOME/.devour")
		viper.SetConfigType("yaml")
		viper.SetConfigName("devour")
	}

	viper.AutomaticEnv()
	viper.SetEnvPrefix("DEVOUR")

	if err := viper.ReadInConfig(); err == nil && verbose {
		fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
	}
}
