package worktree

import (
	"fmt"
	"os"

	"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 removeWorktreeCmd = &cobra.Command{
	Use:     "remove <branch>",
	Aliases: []string{"rm"},
	Short:   "Remove a worktree by branch name",
	Args:    cobra.ExactArgs(1),
	RunE:    runRemoveWorktree,
}

func runRemoveWorktree(cmd *cobra.Command, args []string) error {
	identifier := args[0]

	projectRoot, err := config.FindProjectRoot()
	if err != nil {
		return err
	}
	manager, err := worktree.SetupManager(projectRoot)
	if err != nil {
		return err
	}

	// Resolve worktree by branch name
	wt, err := manager.ResolveWorktree(cmd.Context(), worktree.Identifier(identifier))
	if err != nil {
		return fmt.Errorf("failed to resolve worktree: %w", err)
	}

	// Check for active sessions
	sessionIDs, err := wt.SessionIDs()
	if err != nil {
		// If we can't check sessions, fall back to normal removal with warning
		ui.Warning("Could not check for active sessions: %v", err)
	} else if len(sessionIDs) > 0 && !removeForce {
		// Show error with session information
		ui.Error("Cannot remove worktree '%s' - currently in use by %d session(s):", wt.Branch, len(sessionIDs))

		// TODO: Show detailed session information once we have session manager in CLI
		// For now, just show session IDs
		for _, sessionID := range sessionIDs {
			ui.OutputLine("  - %s", sessionID)
		}

		ui.OutputLine("")
		ui.OutputLine("Use --force to remove anyway, or stop the sessions first")
		return fmt.Errorf("worktree in use")
	}

	// Get current working directory for safety check
	cwd, err := os.Getwd()
	if err != nil {
		return fmt.Errorf("failed to get current directory: %w", err)
	}

	if !removeForce {
		ui.Warning("This will remove worktree with branch '%s'", wt.Branch)
		response := ui.Prompt("Are you sure? (y/N): ")
		if response != "y" && response != "Y" {
			ui.OutputLine("Removal cancelled")
			return nil
		}
	}

	if err := manager.Remove(cmd.Context(), worktree.Identifier(wt.Branch), worktree.RemoveOptions{
		NoHooks:    removeNoHooks,
		CurrentDir: cwd,
	}); err != nil {
		return fmt.Errorf("failed to remove worktree: %w", err)
	}

	ui.Success("Worktree removed successfully: %s", wt.Branch)

	return nil
}
