package commands

import (
	"fmt"
	"net/http"
	"time"

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

var doctorCmd = &cobra.Command{
	Use:   "doctor",
	Short: "Diagnose issues (scan + config check + connectivity)",
	RunE:  runDoctor,
}

func init() {
	rootCmd.AddCommand(doctorCmd)
}

func runDoctor(cmd *cobra.Command, args []string) error {
	fmt.Println("Running Muyue diagnostics...")

	fmt.Println("\n=== System Scan ===")
	result := scanner.ScanSystem()
	for _, t := range result.Tools {
		status := "✓"
		if !t.Installed {
			status = "✗"
		}
		fmt.Printf("  %s %s\n", status, t.Name)
	}
	fmt.Printf("\nInstalled: %d/%d\n", countInstalled(result.Tools), len(result.Tools))

	fmt.Println("\n=== Config Check ===")
	cfg, err := config.Load()
	if err != nil {
		fmt.Printf("  ✗ Failed to load config: %v\n", err)
	} else {
		fmt.Printf("  ✓ Config loaded (version: %s)\n", cfg.Version)
		if cfg.Profile.Name != "" {
			fmt.Printf("  ✓ Profile: %s\n", cfg.Profile.Name)
		}
	}

	fmt.Println("\n=== Connectivity ===")
	endpoints := []string{
		"https://api.minimax.io",
		"https://api.openai.com",
	}
	for _, ep := range endpoints {
		fmt.Printf("  Checking %s... ", ep)
		client := &http.Client{Timeout: 5 * time.Second}
		resp, err := client.Head(ep)
		if err != nil {
			fmt.Printf("✗ (%v)\n", err)
		} else {
			resp.Body.Close()
			fmt.Printf("✓ (status %d)\n", resp.StatusCode)
		}
	}

	fmt.Println("\n=== Diagnosis complete ===")
	return nil
}

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