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

Checks the manifest signature, file hashes and Merkle root, the frozen preregistration and
salts, every signed memory chain, the hypotheses and verdict recomputed from the raw
curves, the gate labels bound to the manifest headline, the checkpoint chain and the
no-model record. The engine is withheld; this verifies 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 = ("portfolio", "portfolio_mdd", "portfolio_strong", "portfolio_mdd_strong")
SALTS = ("primary", "replication")
DROP, FIX, SLACK = 0.10, 0.10, 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(rep, salt, arm): return [float(g["sealed_correct"]) for g in rep["curves"][f"{salt}|{arm}"]]
def reg(s): return sum(1 for a, b in zip(s, s[1:]) if b < a - DROP)
def block(rep, salt):
    a, b = seq(rep, salt, "portfolio"), seq(rep, salt, "portfolio_mdd")
    c, d = seq(rep, salt, "portfolio_strong"), seq(rep, salt, "portfolio_mdd_strong")
    return {"H1": d[-1] >= b[-1] + FIX, "H2": d[-1] >= a[-1] - SLACK,
            "H3": c[-1] >= a[-1], "H4": reg(d) <= reg(a)}


def main():
    b = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    ch = C(); man = load(b / "E443-M_MANIFEST.json"); sig = man.pop("signature", "")
    pub = Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"]))
    try:
        pub.verify(bytes.fromhex(sig), (b / "E443-M_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 = {"E443-M_MANIFEST.json", "E443-M_SIGNED_BODY.json", "E443-M_VERIFICATION_RESULTS.json",
          "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E443-M_OMEGA_SEAL.json",
          "E443-M_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 / "E443-M_PREREGISTRATION_FREEZE.json")
    ch.add("prereg_hash", sha((b / "E443-M_PREREGISTRATION.json").read_bytes())
           == fr.get("preregistration_sha256"), str(fr.get("preregistration_sha256"))[:16])
    salts = load(b / "E443-M_SALT_REVEALED.json")["salts"]; pre = load(b / "E443-M_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 / "E443-M_RUN_REPORT.json")
    hl = man.get("headline") or {}
    ch.add("headline_matches_report",
           hl.get("verdict") == report["verdict"]
           and hl.get("primary_weak_portfolio") == [g["sealed_correct"] for g in report["curves"]["primary|portfolio"]]
           and hl.get("primary_strong_mdd") == [g["sealed_correct"] for g in report["curves"]["primary|portfolio_mdd_strong"]]
           and hl.get("gates") == [g.get("gate") for g in report["curves"]["primary|portfolio_mdd_strong"]],
           "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)
    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 = ("MEASUREMENT_FIXES_GATE" if (prim["H1"] and prim["H2"] and h6)
               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("strong_arms_declare_cost", report["design"].get("dev_worlds_strong") == 24
           and report["design"].get("dev_worlds_weak") == 8, "8 vs 24 development worlds, cost reported")
    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())
