"""Set PR title and body from agent-provided values.

Takes --title and --body (or --body-file) and updates the PR on GitHub,
preserving existing header, footer, and metadata. This command does NOT
call Claude — it applies values already generated by the calling agent.

Usage:
    erk exec set-pr-description --title "Fix auth bug" --body "Fixes the auth issue..."
    erk exec set-pr-description --title "Fix auth bug" --body-file /tmp/body.md

Exit Codes:
    0: Success
    1: Error (no PR, linkage mismatch)
"""

from pathlib import Path

import click

from erk.cli.commands.pr.shared import (
    assemble_pr_body,
    discover_branch_context,
)
from erk.core.plan_context_provider import PlanContextProvider
from erk_shared.context.helpers import require_context
from erk_shared.gateway.github.types import BodyText, PRNotFound


@click.command(name="set-pr-description")
@click.option("--title", required=True, help="PR title")
@click.option("--body", "body_text", default=None, help="PR body text")
@click.option("--body-file", default=None, type=click.Path(exists=True), help="File with PR body")
@click.pass_context
def set_pr_description(
    ctx: click.Context,
    *,
    title: str,
    body_text: str | None,
    body_file: str | None,
) -> None:
    """Update PR title and body with agent-provided values.

    Applies the given title and body to the current branch's PR,
    preserving existing header, footer, and metadata prefix.
    """
    erk_ctx = require_context(ctx)
    cwd = erk_ctx.cwd

    # Resolve body from --body or --body-file
    if body_text is not None:
        pr_body = body_text
    elif body_file is not None:
        pr_body = Path(body_file).read_text(encoding="utf-8")
    else:
        pr_body = ""

    # Discovery
    discovery = discover_branch_context(erk_ctx, cwd=cwd)

    # Find PR
    pr_result = erk_ctx.github.get_pr_for_branch(discovery.repo_root, discovery.current_branch)
    if isinstance(pr_result, PRNotFound):
        raise click.ClickException(
            f"No pull request found for branch '{discovery.current_branch}'\n\n"
            "Create a PR first with `erk exec push-and-create-pr`."
        )

    pr_number = pr_result.number
    existing_body = pr_result.body

    # Plan context for <details> section
    plan_provider = PlanContextProvider(
        plan_backend=erk_ctx.plan_backend, github_issues=erk_ctx.github_issues
    )
    plan_context = plan_provider.get_plan_context(
        repo_root=discovery.repo_root,
        branch_name=discovery.current_branch,
    )

    final_body = assemble_pr_body(
        body=pr_body,
        plan_context=plan_context,
        pr_number=pr_number,
        header="",
        existing_pr_body=existing_body,
        recovered_plan_header=None,
    )

    erk_ctx.github.update_pr_title_and_body(
        repo_root=discovery.repo_root,
        pr_number=pr_number,
        title=title,
        body=BodyText(content=final_body),
    )

    click.echo(f"PR #{pr_number} updated: {title}")
