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 createWorktreeCmd = &cobra.Command{
	Use:   "add <name>",
	Short: "Add a new worktree",
	Long: `Add a new git worktree for isolated development.

Examples:
  # Add worktree with auto-generated branch name
  amux wt add fix-auth

  # Add worktree with new branch
  amux wt add fix-auth -b feature/auth-fix

  # Add worktree from existing branch
  amux wt add fix-auth -c feature/existing-work

  # Add worktree with new branch from specific base
  amux wt add fix-auth --base develop -b feature/auth-fix`,
	Args: cobra.ExactArgs(1),
	RunE: runCreateWorktree,
}

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

	// Validate mutually exclusive flags
	if createBranch != "" && createCheckout != "" {
		return fmt.Errorf("cannot specify both --branch (-b) and --checkout (-c) flags")
	}

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

	opts := worktree.CreateOptions{
		Name:        name,
		BaseBranch:  createBaseBranch,
		Description: createDescription,
		BranchMode:  worktree.BranchModeCreate, // Default to create mode
		NoHooks:     createNoHooks,
	}

	// Set Branch field based on which flag was used
	if createBranch != "" {
		opts.Branch = createBranch
		opts.BranchMode = worktree.BranchModeCreate // Explicit: create new branch
	} else if createCheckout != "" {
		opts.Branch = createCheckout
		opts.BranchMode = worktree.BranchModeCheckout // Explicit: use existing branch
	}

	wt, err := manager.Create(cmd.Context(), opts)
	if err != nil {
		return fmt.Errorf("failed to add worktree: %w", err)
	}

	ui.Success("Worktree added successfully")
	ui.OutputLine("")
	ui.PrintKeyValue("Branch", wt.Branch)
	ui.PrintKeyValue("Path", wt.Path)

	return nil
}
