package commands

import (
	"fmt"

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

var lspCmd = &cobra.Command{
	Use:   "lsp",
	Short: "LSP management",
}

func init() {
	rootCmd.AddCommand(lspCmd)
	lspCmd.AddCommand(&cobra.Command{
		Use:   "scan",
		Short: "Scan for installed LSPs",
		RunE:  runLSPScan,
	})
	lspCmd.AddCommand(&cobra.Command{
		Use:   "install [name]",
		Short: "Install LSP server(s)",
		Args:  cobra.RangeArgs(0, 1),
		RunE:  runLSPInstall,
	})
}

func runLSPScan(cmd *cobra.Command, args []string) error {
	servers := lsp.ScanServers()
	fmt.Printf("%-25s %-15s %-10s\n", "Name", "Language", "Status")
	fmt.Println("──────────────────────────────────────────")
	for _, s := range servers {
		status := "✗ missing"
		if s.Installed {
			status = "✓ installed"
		}
		fmt.Printf("%-25s %-15s %-10s\n", s.Name, s.Language, status)
	}
	return nil
}

func runLSPInstall(cmd *cobra.Command, args []string) error {
	if len(args) == 0 {
		return fmt.Errorf("server name required")
	}
	name := args[0]
	fmt.Printf("Installing %s...\n", name)
	if err := lsp.InstallServer(name); err != nil {
		return err
	}
	fmt.Printf("✓ %s installed\n", name)
	return nil
}