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 listWorktreeCmd = &cobra.Command{
	Use:     "list",
	Aliases: []string{"ls"},
	Short:   "List all worktrees",
	Long: `List all worktrees in the project.

Examples:
  # List worktrees with detailed view
  amux wt ls

  # List worktrees in oneline format for scripting
  amux wt ls --oneline

  # Use with fzf to select a worktree
  amux wt ls --oneline | fzf | cut -f1

  # Remove selected worktree with fzf
  amux wt rm $(amux wt ls --oneline | fzf | cut -f1)`,
	RunE: runListWorktree,
}

func runListWorktree(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
	}

	worktrees, err := manager.List(cmd.Context(), worktree.ListOptions{})
	if err != nil {
		return fmt.Errorf("failed to list worktrees: %w", err)
	}

	// Handle JSON output
	if ui.GlobalFormatter.IsJSON() {
		return ui.GlobalFormatter.Output(worktrees)
	}

	// Handle pretty output
	if listOneline {
		// One line per worktree for fzf integration
		for _, wt := range worktrees {
			// Format: branch<tab>status<tab>path<tab>description
			description := wt.Description
			if description == "" {
				description = "-"
			}

			ui.PrintTSV([][]string{{wt.Branch, wt.Status.String(), wt.Path, description}})
		}
	} else {
		ui.PrintWorktreeList(worktrees)
	}

	return nil
}
