#!/usr/bin/env python3
"""E436-D standalone offline verifier (stdlib + cryptography; imports no CAIN code).

Re-checks the manifest signature, every file hash and the Merkle root, the frozen
preregistration and salts, every signed memory chain, the governance record, the
hypotheses and verdict recomputed from the raw curves, the checkpoint chain and the
no-model record. The engine is withheld; the verifier checks the record, not a re-run.
"""
from __future__ import annotations
import hashlib, json, sys
from pathlib import Path
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey

STATUS = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
ARMS = ("winner", "portfolio", "portfolio_mdd")
SALTS = ("primary", "replication")
DROP, COMPOUND, SLACK = 0.10, 0.20, 0.05


def sha(b: bytes) -> str: return hashlib.sha256(b).hexdigest()
def canon(o) -> bytes: return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()
def load(p): return json.loads(Path(p).read_text())
def derive_pub(a: str) -> bytes:
    k = Ed25519PrivateKey.from_private_bytes(hashlib.sha256(("e380m|" + a).encode()).digest())
    return k.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)


class C:
    def __init__(self): self.rows = []
    def add(self, n, ok, d=""): self.rows.append({"check": n, "ok": bool(ok), "detail": d})
    def finish(self):
        ok = sum(1 for r in self.rows if r["ok"]); n = len(self.rows)
        for r in self.rows: print(f'{"PASS" if r["ok"] else "FAIL"}  {r["check"]}  {r["detail"]}')
        print(f"\n{ok}/{n} checks passed · {STATUS}")
        return 0 if ok == n else 1


def merkle(paths):
    leaves = sorted(sha(p.read_bytes()) for p in paths)
    while len(leaves) > 1:
        if len(leaves) % 2: leaves.append(leaves[-1])
        leaves = [sha((leaves[i] + leaves[i + 1]).encode()) for i in range(0, len(leaves), 2)]
    return leaves[0] if leaves else sha(b"")


def chain(ch, label, rows):
    prev = "0" * 64; ok = sig_ok = canon_ok = True
    for r in rows:
        body = {"tenant": r["tenant"], "seq": r["seq"], "agent": r["agent"], "kind": r["kind"],
                "payload": r["payload"], "uncertainty": r["uncertainty"],
                "verification": r["verification"], "prev": r["prev"]}
        try: h = sha(canon(body) + bytes.fromhex(r["sig"]))
        except Exception: canon_ok = False; break
        if h != r["hash"] or r["prev"] != prev: ok = False; break
        try:
            Ed25519PublicKey.from_public_bytes(derive_pub(r["agent"])).verify(bytes.fromhex(r["sig"]), canon(body))
        except (InvalidSignature, ValueError): sig_ok = False; break
        prev = r["hash"]
    ch.add(f"chain:{label}", ok and canon_ok and sig_ok,
           f"{len(rows)} rows, link={ok}, canonical={canon_ok}, signatures={sig_ok}")


def seq(report, salt, arm): return [float(g["sealed_correct"]) for g in report["curves"][f"{salt}|{arm}"]]
def reg(seq_): return sum(1 for a, b in zip(seq_, seq_[1:]) if b < a - DROP)
def block(report, salt):
    w, p, m = seq(report, salt, "winner"), seq(report, salt, "portfolio"), seq(report, salt, "portfolio_mdd")
    return {"H1": m[-1] >= p[-1] - SLACK, "H2": reg(m) < reg(p), "H3": p[-1] >= w[-1] + COMPOUND,
            "H4": w[-1] <= 0.60}


def main() -> int:
    b = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    ch = C(); man = load(b / "E436-D_MANIFEST.json"); sig = man.pop("signature", "")
    pub = Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"]))
    try:
        pub.verify(bytes.fromhex(sig), (b / "E436-D_SIGNED_BODY.json").read_bytes())
        ch.add("manifest_signature", True, man["pubkey_fingerprint"] + " (self-generated)")
    except (InvalidSignature, ValueError): ch.add("manifest_signature", False, "invalid")

    ex = {"E436-D_MANIFEST.json", "E436-D_SIGNED_BODY.json", "E436-D_VERIFICATION_RESULTS.json",
          "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E436-D_OMEGA_SEAL.json",
          "E436-D_TAMPER_RESULTS.json"}
    files = sorted(x for x in b.rglob("*") if x.is_file() and str(x.relative_to(b)) not in ex
                   and "__pycache__" not in x.parts)
    dec = man.get("files") or {}
    ch.add("file_hashes", all(dec.get(str(x.relative_to(b))) == sha(x.read_bytes()) for x in files)
           and len(dec) == len(files), f"{len(files)} files")
    ch.add("merkle_root", merkle(files) == man.get("merkle_root"), str(man.get("merkle_root"))[:16])

    fr = load(b / "E436-D_PREREGISTRATION_FREEZE.json")
    ch.add("prereg_hash", sha((b / "E436-D_PREREGISTRATION.json").read_bytes())
           == fr.get("preregistration_sha256"), str(fr.get("preregistration_sha256"))[:16])
    salts = load(b / "E436-D_SALT_REVEALED.json")["salts"]; pre = load(b / "E436-D_PREREGISTRATION.json")
    ch.add("salt_commitments", all(sha(bytes.fromhex(v)) == pre["salt_commitment_sha256"][k]
                                    for k, v in salts.items()), "both salts match")

    report = load(b / "E436-D_RUN_REPORT.json")
    hl = man.get("headline") or {}
    ch.add("headline_matches_report",
           hl.get("verdict") == report["verdict"]
           and hl.get("primary_portfolio") == [g["sealed_correct"] for g in report["curves"]["primary|portfolio"]]
           and hl.get("primary_mdd") == [g["sealed_correct"] for g in report["curves"]["primary|portfolio_mdd"]]
           and hl.get("mdd_held") == [g.get("gate") for g in report["curves"]["primary|portfolio_mdd"]],
           "the manifest headline and gate labels are the run report's")
    for s in SALTS:
        for a in ARMS:
            doc = load(b / "memory" / f"{s}-{a}.json"); recs = doc.get("records") or []
            rows = [r for p in recs for r in (p.get("rows") or [])] if recs and "rows" in (recs[0] or {}) else recs
            chain(ch, f"{s}-{a}", rows)

    gov = load(b / "E436-D_GOVERNANCE.json")
    ch.add("governance_h5", report["hypotheses"]["H5"]["verdict"] in ("SUPPORTED", "NOT_SUPPORTED"),
           report["hypotheses"]["H5"]["detail"][:120])

    prim, repl = block(report, "primary"), block(report, "replication")
    h6 = all(prim[k] == repl[k] for k in prim)
    ch.add("hypotheses_recomputed",
           all(report["hypotheses"][k]["verdict"] == ("SUPPORTED" if v else "NOT_SUPPORTED")
               for k, v in prim.items()), "primary H1-H4 follow the raw curves")
    verdict = ("MDD_GATE_SAFE" if (prim["H1"] and h6)
               else "MDD_GATE_BLOCKS_GAIN"
               if seq(report, "primary", "portfolio_mdd")[-1] <= seq(report, "primary", "portfolio")[-1] - COMPOUND
               else "PARTIAL" if sum(prim.values()) >= 3 else "NOT_SUPPORTED")
    ch.add("verdict_recomputed", verdict == report["verdict"], f"{verdict} (report {report['verdict']})")
    ch.add("replication_agrees", h6 == (report["hypotheses"]["H6"]["verdict"] == "SUPPORTED"), "H6")
    ch.add("mdd_used", all(g.get("gate") in ("bootstrap", "held", "promoted")
                            for g in report["curves"]["primary|portfolio_mdd"]),
           "every MDD generation records its gate decision")

    cp = report.get("checkpoints") or []; ok = True; prev = "0" * 64
    for c in cp:
        if c["prev"] != prev: ok = False; break
        body = {k: c[k] for k in ("label", "at", "payload", "prev")}
        prev = sha(json.dumps(body, sort_keys=True, separators=(",", ":")).encode())
        if prev != c["hash"]: ok = False; break
    ch.add("checkpoint_chain", ok, f"{len(cp)} checkpoints")
    d = report.get("design") or {}
    ch.add("no_models_no_spend", d.get("model_calls") == 0 and d.get("api_spend_usd") == 0.0, "0 model calls, $0")
    return ch.finish()


if __name__ == "__main__":
    raise SystemExit(main())
