package commands

import (
	"fmt"

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

var skillsCmd = &cobra.Command{
	Use:   "skills",
	Short: "Skills management",
}

func init() {
	rootCmd.AddCommand(skillsCmd)
	skillsCmd.AddCommand(&cobra.Command{
		Use:   "list",
		Short: "List installed skills",
		RunE:  runSkillsList,
	})
	skillsCmd.AddCommand(&cobra.Command{
		Use:   "init",
		Short: "Install built-in skills",
		RunE:  runSkillsInit,
	})
	skillsCmd.AddCommand(&cobra.Command{
		Use:   "show [name]",
		Short: "Show skill details",
		Args:  cobra.ExactArgs(1),
		RunE:  runSkillsShow,
	})
	skillsCmd.AddCommand(&cobra.Command{
		Use:   "generate [name] [description]",
		Short: "AI-generate a skill",
		Args:  cobra.ExactArgs(2),
		RunE:  runSkillsGenerate,
	})
	skillsCmd.AddCommand(&cobra.Command{
		Use:   "deploy",
		Short: "Deploy skills to Crush/Claude Code",
		RunE:  runSkillsDeploy,
	})
	skillsCmd.AddCommand(&cobra.Command{
		Use:   "delete [name]",
		Short: "Delete a skill",
		Args:  cobra.ExactArgs(1),
		RunE:  runSkillsDelete,
	})
}

func runSkillsList(cmd *cobra.Command, args []string) error {
	list, err := skills.List()
	if err != nil {
		return err
	}
	if len(list) == 0 {
		fmt.Println("No skills installed")
		return nil
	}
	fmt.Printf("%-20s %-40s\n", "Name", "Description")
	fmt.Println("─────────────────────────────────────────────────────")
	for _, s := range list {
		fmt.Printf("%-20s %-40s\n", s.Name, s.Description)
	}
	return nil
}

func runSkillsInit(cmd *cobra.Command, args []string) error {
	fmt.Println("Initializing built-in skills...")
	return nil
}

func runSkillsShow(cmd *cobra.Command, args []string) error {
	name := args[0]
	skill, err := skills.Get(name)
	if err != nil {
		return err
	}
	fmt.Printf("Name: %s\nDescription: %s\nAuthor: %s\nVersion: %s\n\n%s\n",
		skill.Name, skill.Description, skill.Author, skill.Version, skill.Content)
	return nil
}

func runSkillsGenerate(cmd *cobra.Command, args []string) error {
	fmt.Printf("Generating skill '%s': %s\n", args[0], args[1])
	return nil
}

func runSkillsDeploy(cmd *cobra.Command, args []string) error {
	if err := skills.DeployAll(); err != nil {
		return err
	}
	fmt.Println("All skills deployed to Crush and Claude Code")
	return nil
}

func runSkillsDelete(cmd *cobra.Command, args []string) error {
	name := args[0]
	if err := skills.Delete(name); err != nil {
		return err
	}
	fmt.Printf("Skill '%s' deleted\n", name)
	return nil
}