package worktree

import (
	"fmt"

	"github.com/spf13/cobra"

	"github.com/aki/amux/internal/cli/ui"
	"github.com/aki/amux/internal/config"
	worktree "github.com/aki/amux/internal/worktree"
)

var pruneWorktreeCmd = &cobra.Command{
	Use:   "prune",
	Short: "Remove old idle worktrees",
	RunE:  runPruneWorktree,
}

func runPruneWorktree(cmd *cobra.Command, args []string) error {
	projectRoot, err := config.FindProjectRoot()
	if err != nil {
		return err
	}
	manager, err := worktree.SetupManager(projectRoot)
	if err != nil {
		return err
	}

	opts := worktree.CleanupOptions{
		Days:   pruneDays,
		DryRun: pruneDryRun,
	}

	removed, err := manager.Cleanup(cmd.Context(), opts)
	if err != nil {
		return fmt.Errorf("failed to prune worktrees: %w", err)
	}

	if len(removed) == 0 {
		ui.OutputLine("No worktrees to prune")
		return nil
	}

	if pruneDryRun {
		ui.OutputLine("Would remove %d worktree(s):", len(removed))
	} else {
		ui.OutputLine("Removed %d worktree(s)", len(removed))
	}

	for _, id := range removed {
		ui.OutputLine("  - %s", id)
	}

	return nil
}
