"""pjctx handoff — Create a handoff context for another user."""

from __future__ import annotations

from pjctx.core.config import find_repo_root, get_pjctx_dir
from pjctx.core.context import Context
from pjctx.core.git_ops import get_current_branch, get_files_changed, get_diff_summary
from pjctx.core.storage import save_context, load_latest
from pjctx import ui


def run_handoff(obj: dict, user: 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)

    branch = get_current_branch(repo_root)

    # Resolve target user
    target = user
    if target and target.startswith("@"):
        target = target[1:]
    if not target:
        target = ui.prompt("Handoff to (username)")
        if not target:
            ui.error("Username required.")
            raise SystemExit(1)

    # Load previous context to carry forward
    prev = load_latest(repo_root, branch)

    # Gather handoff note
    handoff_note = ui.prompt("Handoff note (what they need to know)")

    files_changed = get_files_changed(repo_root)
    diff_summary = get_diff_summary(repo_root)

    ctx = Context(
        message=f"Handoff to {target}",
        task=prev.task if prev else "",
        approaches_tried=prev.approaches_tried if prev else [],
        current_approach=prev.current_approach if prev else "",
        decisions=prev.decisions if prev else [],
        next_steps=prev.next_steps if prev else [],
        branch=branch,
        files_changed=files_changed,
        git_diff_summary=diff_summary,
        handoff_to=target,
        handoff_note=handoff_note,
        tags=prev.tags if prev else [],
    )

    path = save_context(repo_root, ctx)
    ui.success(f"Handoff context saved for @{target} → {path.name}")
    ui.info("They can run 'pjctx resume' to pick up the context.")
