package cmd

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"
)

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

var updateCmd = &cobra.Command{
	Use:   "update [name]",
	Short: "Pull latest skill versions and write to tool directories",
	Long: `Fetches the latest versions of all skills (or a named skill) from your
airskills account and writes them to each tool's directory.

Reports which skills changed.`,
	Args: cobra.MaximumNArgs(1),
	RunE: runUpdate,
}

func runUpdate(cmd *cobra.Command, args []string) error {
	client, err := newAPIClientAuto()
	if err != nil {
		return err
	}

	var filterName string
	if len(args) == 1 {
		filterName = args[0]
	}

	skills, _, err := client.listPersonalSkillsInSkillset("")
	if err != nil {
		return fmt.Errorf("fetching skills: %w", err)
	}

	syncState := loadSyncState()

	var updated, unchanged int
	for _, skill := range skills {
		if filterName != "" && skill.Name != filterName {
			continue
		}

		files, err := downloadSkillFiles(client, skill.Id.String())
		if err != nil || len(files) == 0 {
			fmt.Fprintf(os.Stderr, "  ! %s: %v\n", skill.Name, err)
			continue
		}

		destinations, err := installSkillToAgents(skill.Name, files)
		if err != nil {
			fmt.Fprintf(os.Stderr, "  ! %s: %v\n", skill.Name, err)
			unchanged++
			continue
		}

		syncState.Skills[skill.Name] = &SyncEntry{
			SkillID:     skill.Id.String(),
			Version:     skill.Version,
			ContentHash: strDeref(skill.ContentHash),
			Tool:        "claude-code",
		}

		fmt.Printf("  updated: %s (%d agents)\n", skill.Name, len(destinations))
		updated++
	}

	saveSyncState(syncState)

	if filterName != "" && updated == 0 && unchanged == 0 {
		return fmt.Errorf("skill %q not found in your account", filterName)
	}

	fmt.Printf("\n%d updated, %d unchanged\n", updated, unchanged)
	_ = saveLastSync()
	return nil
}
