package worktree

import (
	"fmt"
	"os"
	"os/exec"

	"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 cdWorktreeCmd = &cobra.Command{
	Use:   "cd <branch>",
	Short: "Open a subshell in the worktree directory",
	Long: `Open a new shell in the worktree directory. Exit the shell to return to the original directory.

Examples:
  # Enter worktree by branch name
  amux wt cd feature/auth

  # Exit the worktree (in the subshell)
  exit`,
	Args: cobra.ExactArgs(1),
	RunE: runCdWorktree,
}

func runCdWorktree(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)
	}

	// Get user's shell
	shell := os.Getenv("SHELL")
	if shell == "" {
		shell = "/bin/bash"
	}

	// Create a new shell process
	shellCmd := exec.Command(shell)
	shellCmd.Dir = wt.Path
	shellCmd.Stdin = os.Stdin
	shellCmd.Stdout = os.Stdout
	shellCmd.Stderr = os.Stderr

	// Set environment variable to indicate we're in an amux worktree
	shellCmd.Env = append(os.Environ(),
		fmt.Sprintf("AMUX_WORKTREE=%s", wt.Branch),
		fmt.Sprintf("AMUX_WORKTREE_PATH=%s", wt.Path),
	)

	// Print information about entering the worktree
	ui.OutputLine("Entering worktree: %s", wt.Branch)
	ui.PrintKeyValue("Path", wt.Path)
	ui.OutputLine("\nExit the shell to return to your original directory")

	// Run the shell
	if err := shellCmd.Run(); err != nil {
		// Don't treat exit as an error
		if exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() > 0 {
			// User exited with non-zero code, this is fine
			return nil
		}
		return fmt.Errorf("failed to run shell: %w", err)
	}

	return nil
}
