"""pjctx diff — Show changes since last context save."""

from __future__ import annotations

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


def run_diff(obj: dict, stat_only: bool = True) -> 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)
    last_ctx = load_latest(repo_root, branch)

    if last_ctx:
        ui.info(f"Last save: {last_ctx.timestamp[:19]} — {last_ctx.message}")
    else:
        ui.warning("No previous context. Showing all current changes.")

    if stat_only:
        summary = get_diff_summary(repo_root)
        files = get_files_changed(repo_root)
        if not summary and not files:
            ui.info("No changes since last save.")
            return
        if summary:
            ui._console().print(summary)
        if files:
            ui.info("Changed files:")
            for f in files:
                ui._console().print(f"  {f}")
    else:
        full = get_full_diff(repo_root)
        if not full:
            ui.info("No changes since last save.")
            return
        from rich.syntax import Syntax
        syntax = Syntax(full, "diff", theme="monokai")
        ui._console().print(syntax)
