"""pjctx resume — Generate resume prompt and copy to clipboard."""

from __future__ import annotations

from pjctx.core.config import find_repo_root, get_pjctx_dir
from pjctx.core.git_ops import get_current_branch
from pjctx.core.storage import load_latest
from pjctx.prompt import build_prompt
from pjctx import ui


def run_resume(obj: dict, fmt: str = "default", no_copy: bool = False, branch: str | None = None) -> None:
    repo_root = find_repo_root()
    if repo_root is None:
        ui.error("Not inside a git repository.")
        raise SystemExit(1)

    if not get_pjctx_dir(repo_root).exists():
        ui.error("Not initialized. Run 'pjctx init' first.")
        raise SystemExit(1)

    target_branch = branch or get_current_branch(repo_root)
    ctx = load_latest(repo_root, target_branch)

    if ctx is None:
        ui.error(f"No context found for branch '{target_branch}'.")
        ui.info("Run 'pjctx save' to create one.")
        raise SystemExit(1)

    prompt_text = build_prompt(ctx, fmt=fmt)

    if no_copy:
        ui._console().print(prompt_text)
        return

    try:
        import pyperclip
        pyperclip.copy(prompt_text)
        ui.success("Resume prompt copied to clipboard!")
        ui.info(f"Format: {fmt} | Branch: {target_branch}")
        ui.info("Paste it into your AI coding tool to resume.")
    except Exception:
        ui.warning("Could not copy to clipboard (headless environment?).")
        ui.info("Printing to stdout instead:\n")
        ui._console().print(prompt_text)
