"""Hidden command that pre-generates recovery scripts for passthrough flows."""

from pathlib import Path

import click

from erk.cli.core import discover_repo_context
from erk.cli.shell_utils import render_navigation_script
from erk.core.context import ErkContext
from erk_shared.output.output import user_output


def generate_recovery_script(ctx: ErkContext) -> Path | None:
    """Create a recovery script that returns to the repo root if cwd vanishes.

    This helper intentionally guards against runtime cwd races:
    - ctx.cwd is a snapshot from CLI entry; it may no longer exist by the time this runs.
    - discover_repo_context() performs the authoritative repo lookup; probing earlier provides
      no additional safety and merely repeats the work.
    - Returning None signals that graceful degradation is preferred to exploding at the boundary.
    """
    current_dir = ctx.cwd

    if not current_dir.exists():
        return None

    try:
        repo = discover_repo_context(ctx, current_dir)
    except (FileNotFoundError, ValueError):
        return None

    script_content = render_navigation_script(
        repo.root,
        repo.root,
        comment="erk passthrough recovery script",
        success_message="",
    )

    result = ctx.script_writer.write_activation_script(
        script_content,
        command_name="prepare",
        comment="pre-generated by __prepare_cwd_recovery",
    )

    return result.path


@click.command(
    "__prepare_cwd_recovery",
    hidden=True,
    add_help_option=False,
)
@click.pass_obj
def prepare_cwd_recovery_cmd(ctx: ErkContext) -> None:
    """Emit a recovery script if we are inside a managed repository."""
    script_path = generate_recovery_script(ctx)
    if script_path is None:
        return

    user_output(str(script_path), nl=False)
