"""Execute deferred land operations from activation script.

This exec command performs the actual merge and cleanup operations for landing a PR.
It is called by the activation script after the user has approved the operation.

Usage:
    erk exec land-execute --pr-number=123 --branch=foo [options]

All validation happens during the validation phase (erk land). This command
executes the pre-validated operations.

Exit Codes:
    0: Success (PR merged, branch deleted)
    1: Error (merge failed, validation error)
"""

from pathlib import Path

import click

from erk.cli.commands.land_cmd import _execute_land
from erk.cli.commands.objective_helpers import get_objective_for_branch
from erk_shared.context.helpers import require_context


@click.command(name="land-execute")
@click.option(
    "--pr-number",
    type=int,
    required=True,
    help="PR number to merge",
)
@click.option(
    "--branch",
    required=True,
    help="Branch name being landed",
)
@click.option(
    "--worktree-path",
    type=click.Path(),
    help="Path to worktree being cleaned up",
)
@click.option(
    "--is-current-branch",
    is_flag=True,
    help="Whether landing from the branch's own worktree",
)
@click.option(
    "--target-child",
    help="Target child branch for --up navigation",
)
@click.option(
    "--objective-number",
    type=int,
    help="Linked objective issue number",
)
@click.option(
    "--use-graphite",
    is_flag=True,
    help="Use Graphite for merge",
)
@click.option(
    "--pull/--no-pull",
    "pull_flag",
    default=True,
    help="Pull latest changes after landing (default: --pull)",
)
@click.option(
    "--no-delete",
    is_flag=True,
    help="Preserve the local branch and its slot assignment after landing",
)
@click.option(
    "--script",
    is_flag=True,
    help="Output activation script path (for shell integration)",
)
@click.option(
    "--up",
    "up_flag",
    is_flag=True,
    help="Navigate upstack to child branch after landing (resolves child at execution time)",
)
@click.option(
    "-f",
    "--force",
    "force_flag",
    is_flag=True,
    help="Accept flag for compatibility (execute mode always skips confirmations)",
)
@click.pass_context
def land_execute(
    ctx: click.Context,
    *,
    pr_number: int,
    branch: str,
    worktree_path: str | None,
    is_current_branch: bool,
    target_child: str | None,
    objective_number: int | None,
    use_graphite: bool,
    pull_flag: bool,
    no_delete: bool,
    script: bool,
    up_flag: bool,
    force_flag: bool,
) -> None:
    """Execute deferred land operations.

    This command is called by the activation script generated by `erk land`.
    All validation has already been performed - this just executes the
    merge and cleanup operations.

    Confirmations are skipped because the user already approved by sourcing
    the activation script.

    The --up flag resolves the target child branch at execution time (rather than
    baking it into the script at validation time). This allows the user to change
    their stack between validation and execution.
    """
    erk_ctx = require_context(ctx)

    # Resolve --up to target child branch at execution time
    resolved_target_child = target_child
    repo_root = erk_ctx.git.repo.get_repository_root(erk_ctx.cwd)
    if up_flag and target_child is None:
        children = erk_ctx.branch_manager.get_child_branches(repo_root, branch)
        if not children:
            raise click.ClickException(f"Cannot use --up: branch '{branch}' has no children")
        if len(children) > 1:
            children_str = ", ".join(f"'{c}'" for c in children)
            raise click.ClickException(
                f"Cannot use --up: branch '{branch}' has multiple children: {children_str}"
            )
        resolved_target_child = children[0]

    # Auto-detect objective from branch if not explicitly provided
    resolved_objective_number = (
        objective_number
        if objective_number is not None
        else get_objective_for_branch(erk_ctx, repo_root, branch)
    )

    _execute_land(
        erk_ctx,
        pr_number=pr_number,
        branch=branch,
        worktree_path=Path(worktree_path) if worktree_path else None,
        is_current_branch=is_current_branch,
        target_child_branch=resolved_target_child,
        objective_number=resolved_objective_number,
        use_graphite=use_graphite,
        pull_flag=pull_flag,
        no_delete=no_delete,
        script=script,
    )
