#!/usr/bin/env python3
"""check_closure.py -- the Architecture Closure of Unified Field Theory, Version 1.0: every row's source bytes and receipt.
Usage: python3 check_closure.py [path to a clean coppalini-architecture checkout at 312aedb]   (default: source)
Standard library only. For each row it checks the SHA-256 of the cited source bytes, replays the Python receipts it can run
(the UFT receipt is replayed by check_uft.py; the action receipt is replayed here), and prints the row's status:
KERNEL_REPLAYED when a receipt for those exact bytes exists (a local byte-identical replay, or the clean CI run named below on the
pinned commit), OPEN otherwise. A CI run is cited evidence: this script binds the source checkout to that commit and confirms the bytes it compiled."""
import hashlib, os, subprocess, sys
sys.stdout.reconfigure(newline="\n")
REPO = sys.argv[1] if len(sys.argv) > 1 else "source"
COMMIT = "312aedb76dc04216245a2a2f3f0d23f9727ca0be"
CI_011 = "GitHub Actions run 46299956623 (lean-root-to-physics-011, #17, success, commit 312aedb)"
UFT = {"check_uft.py": "fa0872804c950c56175e05e69a33e6761d6a04d51d044f05a9c82193596b5cc7", "RESULTS.txt": "b3c5374e6dda448e8e70934c3d23cf29289ad897a45f3b8014ca6b273475140a"}
SRC = {
    "proofs/RootFieldLift011a.lean": "74f272efe5507678e3463672d2c5fd71a15002f63c0f3b4cfa5dc8ff9e15947c",
    "proofs/SutureSignature011b.lean": "e6ec4e37a1c96bb4c510b8905b04183ce4b6ec7d36ebfcae07e973ecee8fa7ae",
    "proofs/SmoothSuture011c.lean": "33b8aa442da975bcff85425dbea8dea09e86219cbf5ba407f45283ad9475df99",
    "proofs/SutureCovariance011c.lean": "1bdee7a80d6c094d5c4e5243b62fd6608949c7629871c83deb6e6aabf1d3a88a",
    "proofs/SutureRegular011c.lean": "6d7b48da0d88b98410286a954312dcf3427fe4ec1cdaf1d23a9b0fcb39871f52",
    "proofs/SutureOpenBranch011c.lean": "cf87f7ebb9b3e426475ab16db539deeee6db1774dd90a1e01db6b1cc57ecc7b8",
    "proofs/SutureActualMinor011c.lean": "f0541ba474e80dd3164c635f0aace47aaa46533e59631a5ccac7cb69d4fdbdeb",
    "proofs/SutureLDU011c.lean": "71d6b5d2eeb3ec0a5d7373f73dbaf53366da3339f98f596bb09ad06d64134cfd",
    "proofs/SutureLDUCertificate011c.lean": "88ac0b9813a49f031cb54f17eb2a976d33974515c415d6982813ce595e633231",
    "proofs/SutureLDUWitness011c.lean": "1415a43bf55327d037a0eac9e0268060403cb3b0ac368622f7b8adf73fb86580",
    "proofs/SutureLDUEntries011c.lean": "1f0604d78c638b1651c5c9349f2c0b11c9b33d25f2b5947207e3597880756c34",
    "proofs/GaugeMatterTrunk011f.lean": "f274a6163d6695ae72828eb8fce01cca452e39a68df432628864dcdf1a9a6e58",
    "proofs/QuantumStateBoundary011g.lean": "3941f8bae64d20231bede50c8a03a50b27d1f950aa0824d3a69569e2013aaa5f",
    "proofs/ObservableExposure011h.lean": "cedb17868f06775dc990effd2bf3465773aa82b1df5ffeb350540af58006cc32",
    "proofs/GlobalCoverage011i.lean": "cde03df861bdc36366cb1505dd47c6177e16b1e195d9431cad5b0f5f03a859c5",
    "proofs/RootToPhysicsManifest011j.lean": "8dfad7019d94343af5aba2cee26d02483092ae022ded18cc7cbcc849337cda22",
    "proofs/CHSH.lean": "bea123b7643911b1aaffd75f753819b2ad42d28465212c13d2614f67640ff72e",
    "proofs/RootCarrier.lean": "9a73b710327f166734179b25867ddfbb796b8b5c1595c6c6f60a9d3eda1723bb",
    ".github/workflows/lean-root-to-physics-011.yml": "5ab8b082cc2b546b44a1a37b0f0731355876778f2d0d806be053ba735b4b5966",
    ".github/workflows/lean-root-carrier-chsh.yml": "bc29722f30f23b255b0a39347fc7c80809b6827bc3aed630d8692eab1f9c2fe9",
    "proofs/011_ROOT_TO_PHYSICS_INDEX.md": "5618e47ca1b1a5ded601e61ab3bfe285ba3203068cfc00b7c555583ac00dbe46",
    "papers/theory-of-everything/v11/source/receipt/check.py": "a17fbce29a88bd31c9b50e256b9ba2bc1fdf9089e939c1154b4c8a7877887b01",
    "papers/theory-of-everything/v11/source/receipt/RESULTS.txt": "7a1d3c4000a02cd0c00ca61443ff5ccc74253745047d7dff48f8e687c661f6aa",
    "papers/theory-of-everything/v11/source/receipt/check_hamiltonian.py": "7159604f59210faec3a95605cc78d316e6af8019f9996071bf8750448524bc56",
    "papers/theory-of-everything/v11/source/receipt/RESULTS-hamiltonian.txt": "c56906f62492e2d2066904d64913df370eefd5b464e5fbc73023ace185295583",
}
ROWS = [
    ("R1", "Root", "UFT", "ABH", "Q, Omega -> G, eta^, Chat, B, J_Sigma"),
    ("R2", "Coframe", "UFT", "C", "g = Pi^T eta^ Pi, f = chi Pi^T Chat Pi"),
    ("R3", "Seam", "UFT", "D", "B, J_Sigma, transport, joint return (Q^2, I)"),
    ("R4", "Field realization", "UFT", "K", "Einstein-Maxwell-Dirac in the root frame (Theorems 6.1-6.6)"),
    ("R5", "Spin", "UFT", "K", "real Majorana/Dirac matrices, Clifford square eta^, g_Dirac = 2"),
    ("R6", "Reader", "UFT", "F", "Z/4 + Z/137 = Z/548, phi(q, s) = (2 pi/548)(137 q + 4 s)"),
    ("R7", "Regular branch", "CI", ["proofs/RootFieldLift011a.lean", "proofs/SutureSignature011b.lean", "proofs/SmoothSuture011c.lean", "proofs/SutureCovariance011c.lean", "proofs/SutureRegular011c.lean", "proofs/SutureOpenBranch011c.lean", "proofs/SutureActualMinor011c.lean", "proofs/SutureLDU011c.lean", "proofs/SutureLDUCertificate011c.lean", "proofs/SutureLDUWitness011c.lean", "proofs/SutureLDUEntries011c.lean", ".github/workflows/lean-root-to-physics-011.yml"], "selected minor det DS_{Pi*}[I, J] = 368640 != 0, rank DS_Pi = 16 on an open branch"),
    ("R8", "Action", "LOCAL", ["papers/theory-of-everything/v11/source/receipt/check.py", "papers/theory-of-everything/v11/source/receipt/RESULTS.txt", "papers/theory-of-everything/v11/source/receipt/check_hamiltonian.py", "papers/theory-of-everything/v11/source/receipt/RESULTS-hamiltonian.txt"], "axial Euler-Lagrange z'' = z of L = (1/2) z'^T H z' + (1/2) z^T H z, Noether invariants E, J"),
    ("R9", "Correlation", "NONE", ["proofs/CHSH.lean", "proofs/RootCarrier.lean", ".github/workflows/lean-root-carrier-chsh.yml"], "CHSH witness on the root carrier"),
    ("R10", "Gauge ledger", "CI", ["proofs/GaugeMatterTrunk011f.lean", ".github/workflows/lean-root-to-physics-011.yml"], "sl3 + sl2 + u1 (8 + 3 + 1 = 12), 66-dim pair ledger, Higgs mass identities, 19-coordinate register"),
    ("R11", "Empirical gate", "CI", ["proofs/QuantumStateBoundary011g.lean", "proofs/ObservableExposure011h.lean", "proofs/GlobalCoverage011i.lean", "proofs/RootToPhysicsManifest011j.lean", "proofs/011_ROOT_TO_PHYSICS_INDEX.md", ".github/workflows/lean-root-to-physics-011.yml"], "frozen-declaration admission of calibrated records; obligation ledger and manifest (ledger only; its named offices stay open)"),
]
OK = True
counts = {"KERNEL_REPLAYED": 0, "OPEN": 0}
sha = lambda p: hashlib.sha256(open(p, "rb").read()).hexdigest() if os.path.isfile(p) else None
here = os.path.dirname(os.path.abspath(__file__))
uft_ok = all(sha(os.path.join(here, f)) == h for f, h in UFT.items())
res = open(os.path.join(here, "RESULTS.txt")).read() if uft_ok else ""


def checkout_state(root):
    """Bind the supplied source to the declared commit and a clean tree."""
    try:
        head = subprocess.run(
            ["git", "-C", root, "rev-parse", "HEAD"],
            capture_output=True,
            text=True,
            check=True,
        ).stdout.strip()
        clean = subprocess.run(["git", "-C", root, "diff", "--quiet"], capture_output=True).returncode == 0
        staged = subprocess.run(["git", "-C", root, "diff", "--cached", "--quiet"], capture_output=True).returncode == 0
        return head == COMMIT and clean and staged, head
    except (OSError, subprocess.CalledProcessError):
        return False, "unavailable"


repo_ok, repo_head = checkout_state(REPO)
for rid, office, kind, ref, content in ROWS:
    if kind == "UFT":
        ok = uft_ok and res.rstrip().endswith("RESULT PASS") and all(any(l.startswith("PASS " + s) for l in res.splitlines()) for s in ref)
        status, why = "KERNEL_REPLAYED", "UFT receipt, sections " + ", ".join(ref) + " (check_uft.py, RESULTS.txt pinned by SHA-256)"
    else:
        bad = [] if repo_ok else ["checkout=" + repo_head]
        bad += [p for p in ref if sha(os.path.join(REPO, p)) != SRC[p]]
        ok = not bad
        if kind == "LOCAL" and ok:
            d = os.path.join(REPO, "papers/theory-of-everything/v11/source/receipt")
            outs = [subprocess.run([sys.executable, "-B", s], cwd=d, capture_output=True).stdout for s in ("check.py", "check_hamiltonian.py")]
            ok = outs[0] == open(os.path.join(d, "RESULTS.txt"), "rb").read() and outs[1] == open(os.path.join(d, "RESULTS-hamiltonian.txt"), "rb").read()
        status = {"CI": "KERNEL_REPLAYED", "LOCAL": "KERNEL_REPLAYED", "NONE": "OPEN"}[kind]
        why = {"CI": CI_011, "LOCAL": "ToE v11 receipt and Hamiltonian receipt replayed here, byte-identical", "NONE": "source bytes pinned; no compiler receipt pinned to these bytes yet"}[kind]
        why += "; %d source files pinned%s" % (len(ref), "" if ok else " (mismatch: " + ", ".join(bad) + ")")
    OK = OK and ok
    counts[status] += 1 if ok else 0
    print(("PASS " if ok else "FAIL ") + "%s %s [%s]: %s -- %s" % (rid, office, status, content, why))
print("STATUS KERNEL_REPLAYED=%d OPEN=%d" % (counts["KERNEL_REPLAYED"], counts["OPEN"]))
print("RESULT " + ("PASS" if OK else "FAIL"))
sys.exit(0 if OK else 1)
