# stamp_verify.py — content_sha256 selftest (G-024(b) / E-024: hash via script-file ONLY)
# Recompute canonical body-hash of broadcast/email .md and compare vs declared frontmatter.
# Canonical (Harness-3 §N / README): strip \r -> split at 2nd '---' line -> strip ONE leading newline -> sha256 utf-8.
# Also prints the NO-STRIP variant to diagnose wrong-method stamps (BVAAU s71 finding class).
# Usage: python scripts/stamp_verify.py <file.md> [...]   exit 1 if any MISMATCH.
# mirror-of AI_INFRA/scripts/stamp_verify.py (ported S141 2026-07-20) - re-pull khi hub đổi §N canon. KHONG sửa logic local.

import hashlib
import re
import sys
from pathlib import Path


def analyze(p: Path):
    raw = p.read_bytes().decode("utf-8", errors="replace")
    m = re.search(r'content_sha256:\s*"?([0-9a-fA-F]{8,64})"?', raw)
    declared = m.group(1).lower() if m else None
    text = raw.replace("\r", "")
    parts = re.split(r"(?m)^---\s*$", text, maxsplit=2)
    if len(parts) < 3:
        return declared, None, None
    body_nostrip = parts[2]
    body_canon = re.sub(r"^\n", "", body_nostrip, count=1)
    h_canon = hashlib.sha256(body_canon.encode("utf-8")).hexdigest()
    h_nostrip = hashlib.sha256(body_nostrip.encode("utf-8")).hexdigest()
    return declared, h_canon, h_nostrip


def main():
    if len(sys.argv) < 2:
        print("usage: python scripts/stamp_verify.py <file.md> [...]")
        sys.exit(2)
    bad = 0
    for arg in sys.argv[1:]:
        p = Path(arg)
        declared, h_canon, h_nostrip = analyze(p)
        print(f"\n== {p.name}")
        print(f"   declared : {declared}")
        print(f"   canonical: {h_canon}")
        print(f"   no-strip : {h_nostrip}")
        if declared is None:
            print("   verdict  : NO-DECLARED-SHA (n/a)")
        elif h_canon and (h_canon.startswith(declared) or declared.startswith(h_canon[: len(declared)])):
            print("   verdict  : OK (canonical match)")
        elif h_nostrip and (h_nostrip.startswith(declared) or declared.startswith(h_nostrip[: len(declared)])):
            print("   verdict  : WRONG-METHOD (declared = NO-STRIP variant -> re-stamp canonical)")
            bad += 1
        else:
            print("   verdict  : MISMATCH (neither variant -> investigate: edit-after-stamp?)")
            bad += 1
    sys.exit(1 if bad else 0)


if __name__ == "__main__":
    main()
