package commands

import (
	"encoding/json"
	"fmt"

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

var scanCmd = &cobra.Command{
	Use:   "scan",
	Short: "Run system scan and print results table",
	RunE:  runScan,
}

func init() {
	rootCmd.AddCommand(scanCmd)
	scanCmd.Flags().Bool("json", false, "Output results as JSON")
}

func runScan(cmd *cobra.Command, args []string) error {
	useJSON, _ := cmd.Flags().GetBool("json")
	result := scanner.ScanSystem()

	if useJSON {
		data, err := json.MarshalIndent(result, "", "  ")
		if err != nil {
			return err
		}
		fmt.Println(string(data))
		return nil
	}

	fmt.Printf("%-15s %-20s %-10s %-10s\n", "Tool", "Version", "Status", "Path")
	fmt.Println("─────────────────────────────────────────────────")
	for _, t := range result.Tools {
		status := "✓ installed"
		if !t.Installed {
			status = "✗ missing"
		}
		fmt.Printf("%-15s %-20s %-10s %-10s\n", t.Name, t.Version, status, t.Path)
	}
	fmt.Printf("\n%  d/%d tools installed\n", len(result.Tools) - countMissing(result.Tools), len(result.Tools))
	return nil
}

func countMissing(tools []scanner.ToolStatus) int {
	missing := 0
	for _, t := range tools {
		if !t.Installed {
			missing++
		}
	}
	return missing
}