"""pjctx save — Save current context (interactive / quick / auto)."""

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_save(
    obj: dict,
    message: str | None = None,
    auto_mode: bool = False,
    tags: list[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)
    files_changed = get_files_changed(repo_root)
    diff_summary = get_diff_summary(repo_root)

    if auto_mode:
        ctx = _auto_save(repo_root, branch, files_changed, diff_summary, tags or [])
    elif message:
        ctx = _quick_save(branch, message, files_changed, diff_summary, tags or [])
    else:
        ctx = _interactive_save(repo_root, branch, files_changed, diff_summary, tags or [])

    path = save_context(repo_root, ctx)
    ui.success(f"Context saved → {path.name}")
    ui.print_context_brief(ctx.to_dict())


def _quick_save(
    branch: str,
    message: str,
    files_changed: list[str],
    diff_summary: str,
    tags: list[str],
) -> Context:
    return Context(
        message=message,
        branch=branch,
        files_changed=files_changed,
        git_diff_summary=diff_summary,
        tags=tags,
    )


def _auto_save(
    repo_root,
    branch: str,
    files_changed: list[str],
    diff_summary: str,
    tags: list[str],
) -> Context:
    """Auto-fill from git, carry forward previous context fields."""
    prev = load_latest(repo_root, branch)
    if prev:
        return Context(
            message=prev.message or "Auto-save",
            task=prev.task,
            approaches_tried=prev.approaches_tried,
            current_approach=prev.current_approach,
            decisions=prev.decisions,
            next_steps=prev.next_steps,
            branch=branch,
            files_changed=files_changed,
            git_diff_summary=diff_summary,
            tags=tags or prev.tags,
        )
    return Context(
        message="Auto-save",
        branch=branch,
        files_changed=files_changed,
        git_diff_summary=diff_summary,
        tags=tags,
    )


def _interactive_save(
    repo_root,
    branch: str,
    files_changed: list[str],
    diff_summary: str,
    tags: list[str],
) -> Context:
    """Walk through each field interactively with Rich prompts."""
    ui.info(f"Saving context for branch: [cyan]{branch}[/]")
    ui.info(f"Files changed: {len(files_changed)}")

    # Pre-fill from previous context if available
    prev = load_latest(repo_root, branch)

    message = ui.prompt(
        "Summary message",
        default=prev.message if prev else "",
    )
    task = ui.prompt(
        "Current task",
        default=prev.task if prev else "",
    )
    current_approach = ui.prompt(
        "Current approach",
        default=prev.current_approach if prev else "",
    )
    approaches_tried = ui.prompt_list(
        "Approaches tried",
    )
    if not approaches_tried and prev and prev.approaches_tried:
        if ui.confirm("Carry forward previous approaches tried?", default=True):
            approaches_tried = prev.approaches_tried

    decisions = ui.prompt_list("Key decisions")
    if not decisions and prev and prev.decisions:
        if ui.confirm("Carry forward previous decisions?", default=True):
            decisions = prev.decisions

    next_steps = ui.prompt_list("Next steps")

    if not tags:
        tags = ui.prompt_list("Tags")

    return Context(
        message=message,
        task=task,
        approaches_tried=approaches_tried,
        current_approach=current_approach,
        decisions=decisions,
        next_steps=next_steps,
        branch=branch,
        files_changed=files_changed,
        git_diff_summary=diff_summary,
        tags=tags,
    )
