package commands

import (
	"fmt"

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

var updateCmd = &cobra.Command{
	Use:   "update [tool]",
	Short: "Check and apply updates",
	Args:  cobra.RangeArgs(0, 1),
	RunE:  runUpdate,
}

var checkOnly bool

func init() {
	rootCmd.AddCommand(updateCmd)
	updateCmd.Flags().BoolVar(&checkOnly, "check", false, "Check only, don't update")
}

func runUpdate(cmd *cobra.Command, args []string) error {
	result := scanner.ScanSystem()
	statuses := updater.CheckUpdates(result)

	if len(args) > 0 {
		for _, u := range statuses {
			if u.Tool == args[0] {
				if u.NeedsUpdate {
					fmt.Printf("%s: %s → %s\n", u.Tool, u.Current, u.Latest)
					if !checkOnly {
						updater.RunAutoUpdate([]updater.UpdateStatus{u})
						fmt.Println("Updated!")
					}
				} else {
					fmt.Printf("%s is up to date (%s)\n", u.Tool, u.Current)
				}
				return nil
			}
		}
		fmt.Printf("Tool '%s' not found\n", args[0])
		return nil
	}

	fmt.Printf("%-15s %-10s %-10s %-10s\n", "Tool", "Current", "Latest", "Status")
	fmt.Println("─────────────────────────────────────────")
	hasUpdates := false
	for _, u := range statuses {
		status := "✓"
		if u.NeedsUpdate {
			status = "⟳ update"
			hasUpdates = true
		}
		if u.Error != "" {
			status = "✗ " + u.Error
		}
		fmt.Printf("%-15s %-10s %-10s %-10s\n", u.Tool, u.Current, u.Latest, status)
	}

	if checkOnly {
		return nil
	}

	if hasUpdates {
		toUpdate := make([]updater.UpdateStatus, 0)
		for _, u := range statuses {
			if u.NeedsUpdate {
				toUpdate = append(toUpdate, u)
			}
		}
		updater.RunAutoUpdate(toUpdate)
		fmt.Println("\nUpdates applied.")
	} else {
		fmt.Println("\nAll tools are up to date.")
	}
	return nil
}