// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package cmd

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

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

var (
	cfgFile   string
	serverURL string
	token     string
	verbose   bool

	version   string
	buildTime string
	gitCommit string
)

// rootCmd represents the base command
var rootCmd = &cobra.Command{
	Use:   "gitea-cli",
	Short: "A CLI tool for Gitea",
	Long: `gitea-cli is a command-line tool for interacting with Gitea instances.

It provides efficient chunked uploads for large files, progress tracking,
and the ability to resume interrupted uploads.

Example usage:
  gitea-cli auth login --server https://gitea.example.com
  gitea-cli upload release-asset --repo owner/repo --release v1.0.0 --file ./app.tar.gz
  gitea-cli upload resume --session sess_abc123`,
}

// Execute runs the root command
func Execute() error {
	return rootCmd.Execute()
}

// SetVersion sets version information
func SetVersion(v, bt, gc string) {
	version = v
	buildTime = bt
	gitCommit = gc
}

func init() {
	cobra.OnInitialize(initConfig)

	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.gitea-cli.yaml)")
	rootCmd.PersistentFlags().StringVarP(&serverURL, "server", "s", "", "Gitea server URL")
	rootCmd.PersistentFlags().StringVarP(&token, "token", "t", "", "API token")
	rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "verbose output")

	_ = viper.BindPFlag("server", rootCmd.PersistentFlags().Lookup("server"))
	_ = viper.BindPFlag("token", rootCmd.PersistentFlags().Lookup("token"))

	// Add subcommands
	rootCmd.AddCommand(versionCmd)
	rootCmd.AddCommand(authCmd)
	rootCmd.AddCommand(uploadCmd)
}

func initConfig() {
	if cfgFile != "" {
		viper.SetConfigFile(cfgFile)
	} else {
		home, err := os.UserHomeDir()
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			return
		}

		viper.AddConfigPath(home)
		viper.AddConfigPath(filepath.Join(home, ".config", "gitea-cli"))
		viper.SetConfigName(".gitea-cli")
		viper.SetConfigType("yaml")
	}

	viper.SetEnvPrefix("GITEA")
	viper.AutomaticEnv()

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

// versionCmd shows version information
var versionCmd = &cobra.Command{
	Use:   "version",
	Short: "Print version information",
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Printf("gitea-cli version %s\n", version)
		fmt.Printf("  Build time: %s\n", buildTime)
		fmt.Printf("  Git commit: %s\n", gitCommit)
	},
}

// getServer returns the configured server URL
func getServer() string {
	if serverURL != "" {
		return serverURL
	}
	return viper.GetString("server")
}

// getToken returns the configured API token
func getToken() string {
	if token != "" {
		return token
	}
	return viper.GetString("token")
}
