package commands

import (
	"fmt"

	"github.com/muyue/muyue/internal/installer"
	"github.com/muyue/muyue/internal/scanner"
	"github.com/spf13/cobra"
)

var installCmd = &cobra.Command{
	Use:   "install [tool]",
	Short: "Install missing tools",
	Args:  cobra.RangeArgs(0, 1),
	RunE:  runInstall,
}

var installYes bool

func init() {
	rootCmd.AddCommand(installCmd)
	installCmd.Flags().BoolVar(&installYes, "yes", false, "Skip confirmation")
}

func runInstall(cmd *cobra.Command, args []string) error {
	var tools []string
	if len(args) > 0 {
		tools = args
	}

	inst := installer.New(nil)
	if len(tools) == 0 {
		result := scanner.ScanSystem()
		for _, t := range result.Tools {
			if !t.Installed {
				tools = append(tools, t.Name)
			}
		}
		if len(tools) == 0 {
			fmt.Println("All tools already installed!")
			return nil
		}
		fmt.Printf("Installing missing tools: %v\n", tools)
	}

	for _, tool := range tools {
		fmt.Printf("Installing %s...\n", tool)
		res := inst.InstallTool(tool)
		if res.Success {
			fmt.Printf("✓ %s: %s\n", tool, res.Message)
		} else {
			fmt.Printf("✗ %s: %s\n", tool, res.Message)
		}
	}
	return nil
}