"""pjctx log — Show context history."""

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 list_contexts, list_branches
from pjctx import ui


def run_log(obj: dict, branch: str | None = None, limit: int = 10, all_branches: bool = False) -> 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)

    if all_branches:
        branches = list_branches(repo_root)
        if not branches:
            ui.warning("No contexts found.")
            return
        for b in branches:
            _show_branch_log(repo_root, b, limit)
    else:
        target = branch or get_current_branch(repo_root)
        _show_branch_log(repo_root, target, limit)


def _show_branch_log(repo_root, branch: str, limit: int) -> None:
    contexts = list_contexts(repo_root, branch)
    if not contexts:
        ui.warning(f"No contexts for branch '{branch}'.")
        return

    # Show most recent first, limited
    contexts = list(reversed(contexts))[:limit]

    rows: list[list[str]] = []
    for ctx in contexts:
        ts = ctx.timestamp[:19] if ctx.timestamp else ""
        msg = ctx.message[:60] if ctx.message else ""
        files = str(len(ctx.files_changed))
        tags = ", ".join(ctx.tags) if ctx.tags else ""
        rows.append([ts, msg, files, tags])

    ui.print_table(
        title=f"Context Log — {branch}",
        columns=["Timestamp", "Message", "Files", "Tags"],
        rows=rows,
    )
