#!/usr/bin/env python3
"""Optional git-level guard: journal append-only, enforced for ANY runtime.

Refuses a commit that modifies, deletes, or renames-away an EXISTING entry under
20_memory/journal/. Adding a new entry is allowed (append-only). This is defence in depth for the
journal-guard reflex - it holds even when the agent runtime has no hook system at all, and it also
guards against a human slip.

Install (per clone, deliberate):
    cp core/git-hooks/pre-commit .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit

Bypass (deliberate, audited by git history itself): git commit --no-verify
"""
import subprocess
import sys

JOURNAL_PREFIX = "20_memory/journal/"


def main():
    out = subprocess.run(
        ["git", "diff", "--cached", "--name-status", "-M"],
        capture_output=True, text=True, check=True).stdout
    offences = []
    for line in out.splitlines():
        parts = line.split("\t")
        if len(parts) < 2:
            continue
        status, paths = parts[0], parts[1:]
        # A = new file (allowed). M/D = modify/delete (blocked). R/C carry old+new paths;
        # renaming an entry away from the journal is blocked via the OLD path.
        if status.startswith("A"):
            continue
        for p in paths:
            if p.startswith(JOURNAL_PREFIX) and not p.endswith("README.md") \
                    and not p.endswith(".gitkeep"):
                offences.append(f"  {status}\t{p}")
                break
    if offences:
        sys.stderr.write(
            "[journal-guard/pre-commit] 20_memory/journal/ is append-only and immutable.\n"
            "This commit would modify, delete, or move existing journal entries:\n"
            + "\n".join(offences) + "\n"
            "A correction or retraction is a NEW entry. Unstage these changes to proceed.\n")
        sys.exit(1)
    sys.exit(0)


if __name__ == "__main__":
    main()
