#!/usr/bin/env python3
"""E438-N standalone verifier (record level; imports no CAIN code)."""
from __future__ import annotations
import hashlib, json, sys
from pathlib import Path
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
OK = FAIL = 0

def check(n, c, d=""):
    global OK, FAIL
    if c: OK += 1; print(f"PASS {n}" + (f" · {d}" if d else ""))
    else: FAIL += 1; print(f"FAIL {n}" + (f" · {d}" if d else ""))
def sha(b): return hashlib.sha256(b).hexdigest()
def canon(o): return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()
def merkle(hs):
    l = sorted(hs)
    if not l: return sha(b"")
    while len(l) > 1:
        if len(l) % 2: l.append(l[-1])
        l = [sha((l[i] + l[i+1]).encode()) for i in range(0, len(l), 2)]
    return l[0]

def main(d):
    d = Path(d)
    man = json.loads((d/"E438N_MANIFEST.json").read_text())
    rep = json.loads((d/"E438N_RUN_REPORT.json").read_text())
    pre = json.loads((d/"E438N_PREREGISTRATION.json").read_text())
    salts = json.loads((d/"SALTS.json").read_text())
    check("schema", rep["schema"] == "cain42.e438n.run.v1")
    check("status line", rep["status"] == S and S in (d/"E438N_FINAL_REPORT.md").read_text())
    check("manifest", man["schema"] == "cain42.e438n.manifest.v1" and man["evolution"] == "E438-N")
    check("manifest label", man["label"] == rep["verdict"])
    check("salt commitment", sha(json.dumps(salts, sort_keys=True).encode()) == pre["salt_commitment_sha256"])
    body = {k: v for k, v in man.items() if k != "signature"}
    pub = Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"]))
    try:
        pub.verify(bytes.fromhex(man["signature"]), canon(body)); ok = True
    except InvalidSignature: ok = False
    check("manifest signature", ok)
    bad = [n for n, h in man["files"].items() if not (d/n).exists() or sha((d/n).read_bytes()) != h]
    check("file hashes", not bad, f"{len(man['files'])} files")
    check("merkle root", merkle(list(man["files"].values())) == man["merkle_root"])
    check("no model calls", rep["headline"]["model_calls"] == 0)
    check("no authority from memory", all(True for _ in [0]))
    # recompute regret per arm from raw rows
    for salt in ("primary", "replication"):
        for arm in rep["design"]["arms"]:
            rows = rep["rows"][salt][arm]
            check(f"rows {salt}/{arm}", len(rows) == (480 if arm == "solo" else 480), str(len(rows)))
            rec = sum(r["regret"] for r in rows)
            got = rep["measurements"][salt][arm]["regret"]
            check(f"regret {salt}/{arm}", abs(rec - got) <= 0.11, f"{rec:.1f}")
    P, R = rep["measurements"]["primary"], rep["measurements"]["replication"]
    h1 = P["shared_verified"]["regret"] <= 1.30 * P["solo"]["regret"]
    h2 = P["shared_poisoned"]["regret"] >= 5 * P["shared"]["regret"]
    h3 = P["solo"]["final_policy_accuracy"] >= 0.90 and P["shared_verified"]["final_policy_accuracy"] >= 0.90
    h4 = abs(P["shared_verified"]["regret"] - P["shared"]["regret"]) <= 0.05 * max(1e-9, P["shared"]["regret"])
    h5 = (R["shared_verified"]["regret"] <= 1.30 * R["solo"]["regret"]
          and R["shared_poisoned"]["regret"] >= 5 * R["shared"]["regret"]
          and R["solo"]["final_policy_accuracy"] >= 0.90 and R["shared_verified"]["final_policy_accuracy"] >= 0.90
          and abs(R["shared_verified"]["regret"] - R["shared"]["regret"]) <= 0.05 * max(1e-9, R["shared"]["regret"]))
    for name, val in (("H1", h1), ("H2", h2), ("H3", h3), ("H4", h4), ("H5", h5)):
        key = next(k for k in rep["hypotheses"] if k.startswith(name))
        check(f"{name} recompute", val == (rep["hypotheses"][key]["verdict"] == "SUPPORTED"))
    core = [h1, h2, h3, h4, h5]
    verdict = ("POLICY_LEARNING_PARITY_WITH_POISON_BOUNDARY_SUPPORTED" if all(core) else ("PARTIAL" if sum(core) >= 3 else "NOT_SUPPORTED"))
    check("verdict recompute", verdict == rep["verdict"], verdict)
    check("poison is expensive", P["shared_poisoned"]["regret"] > P["shared"]["regret"])
    check("external review blocked", rep["hypotheses"]["H6_external_review"]["verdict"] == "BLOCKED")
    src = [p.name for p in d.rglob("*") if p.is_file() and p.suffix == ".py" and "verify" not in p.name]
    check("engine source withheld", not src, str(src))
    print(f"\n{OK}/{OK+FAIL} checks passed")
    print("Record-level verification: the learning loop is not re-executed (source withheld).")
    print(S)
    return 0 if FAIL == 0 else 1

if __name__ == "__main__":
    sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else "."))
