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

Recomputes every hypothesis and the verdict from the 432 raw run rows, checks the salt
commitments, the use accounting, the SHA-256 trace chain, the manifest signature and the
Merkle root.
"""
import hashlib
import json
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
ENG = ("core.py", "lease.py", "run.py")
EX = {"E331L_MANIFEST.json", "E331L_SIGNED_BODY.json", "E331L_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E331L_OMEGA_SEAL.json",
      "E331L_TAMPER_RESULTS.json", "E331L_ACCEPTANCE_REGISTRY.json"}


def canon(o):
    return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()


def sha(b):
    return hashlib.sha256(b).hexdigest()


def merkle(paths):
    leaves = sorted(sha(p.read_bytes()) for p in paths)
    if not leaves:
        return sha(b"")
    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]


def chain(rows):
    prev = "0" * 64
    out = []
    for r in rows:
        h = sha((prev + sha(canon(r))).encode())
        out.append({"i": len(out), "prev": prev, "hash": h})
        prev = h
    return out


def main():
    B = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    c = []

    def ck(n, ok, d=""):
        c.append({"check": n, "ok": bool(ok), "detail": str(d)[:300]})

    man = json.loads((B / "E331L_MANIFEST.json").read_text())
    ck("schema", man.get("schema") == "cain42.e331l.manifest.v1")
    ck("status", man.get("status") == S)
    body = {k: v for k, v in man.items() if k != "signature"}
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
            bytes.fromhex(man["signature"]), canon(body))
        ck("signature", True)
    except Exception as ex:
        ck("signature", False, ex)
    files = man.get("files", {})
    ck("files present", all((B / k).exists() for k in files))
    ck("file hashes", not [k for k, h in files.items()
                           if (B / k).exists() and sha((B / k).read_bytes()) != h])
    ck("merkle", merkle(sorted(B / k for k in files if (B / k).exists())) == man.get("merkle_root"))
    present = {str(x.relative_to(B)) for x in B.rglob("*")
               if x.is_file() and "__pycache__" not in x.parts}
    ck("no unlisted file", not (present - set(files) - EX), sorted(present - set(files) - EX)[:5])
    ck("source withheld", not any((B / n).exists() for n in ENG))

    pre = json.loads((B / "E331L_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E331L_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E331L_RUN_REPORT.json").read_text())
    rev = json.loads((B / "E331L_SALT_REVEALED.json").read_text())
    ck("prereg hash", sha((B / "E331L_PREREGISTRATION.json").read_bytes()) ==
       frz["preregistration_sha256"])
    ck("freeze before run", frz["frozen_at"] <= rep["generated_at"])
    ck("salt commitments", all(sha(bytes.fromhex(rev["salts"][k])) ==
                               pre["salt_commitment_sha256"][k] for k in rev["salts"]))
    ck("external not faked",
       json.loads((B / "E331L_EXTERNAL_REVIEW_STATUS.json").read_text()).get("status") == "NOT_OBTAINED")
    ck("engine hashes", len(pre.get("engine_sha256", {})) == len(ENG))
    ck("pinned dependency", len(pre.get("dependency_sha256", {})) == 2)

    allr = []
    for salt in ("primary", "replication"):
        rows = rep["sets"][salt]["rows"]
        allr += rows
        ck(f"{salt} rows", len(rows) == 216, len(rows))
        ck(f"{salt} unique", len({(r["grammar"], r["world"], r["cell"], r["arm"])
                                  for r in rows}) == 216)
    ck("total runs", len(allr) == 432, len(allr))
    ck("use accounting", all(r["correct_uses"] + r["wrong_uses"] + r["refused_uses"] == 60
                             for r in allr))
    drift = [r for r in allr if r["cell"] != "static"]
    static = [r for r in allr if r["cell"] == "static"]
    ck("drift/static split", len(drift) == 288 and len(static) == 144)
    ck("drift admitted", all(r["diff_rate"] >= 0.05 - 1e-9 for r in drift))
    ck("static no drift", all(r["diff_rate"] == 0 for r in static))

    def arm(rows, name):
        return [r for r in rows if r["arm"] == name]

    def mean(rows, key):
        xs = [r[key] for r in rows if r.get(key) is not None]
        return (sum(xs) / len(xs)) if xs else 0.0

    perm = arm(drift, "PERMANENT")
    h1 = (sum(1 for r in perm if r["wrong_uses"] >= 25) / len(perm)) >= 0.90
    l8 = arm(drift, "LEASE_8")
    h2 = mean(l8, "wrong_uses") <= 2.0 and mean(l8, "refused_uses") <= 12
    l2, l20 = arm(drift, "LEASE_2"), arm(drift, "LEASE_20")
    h3 = (mean(l2, "wrong_uses") >= mean(l8, "wrong_uses") >= mean(l20, "wrong_uses") and
          mean(l2, "lease_labels") < mean(l8, "lease_labels") < mean(l20, "lease_labels"))
    b5 = arm(drift, "LEASE_8_BATCH5")
    h4 = (mean(b5, "lease_labels") <= 0.40 * mean(l8, "lease_labels") and
          mean(b5, "wrong_uses") <= 8.0)
    h5 = (sum(r["false_revocations"] for r in static) == 0 and
          all(r["correct_uses"] == 60 for r in static))
    rd = [r for r in rep["sets"]["replication"]["rows"] if r["cell"] != "static"]
    r8, rb5 = arm(rd, "LEASE_8"), arm(rd, "LEASE_8_BATCH5")
    h6 = (mean(r8, "wrong_uses") <= 2.0 and mean(r8, "refused_uses") <= 12 and
          mean(rb5, "lease_labels") <= 0.40 * mean(r8, "lease_labels") and
          mean(rb5, "wrong_uses") <= 8.0)
    H = rep["hypotheses"]
    for k, ok in (("H1_permanent_unsafe", h1), ("H2_lease8_safe", h2),
                  ("H3_cost_safety_frontier", h3), ("H4_batch_bounded", h4),
                  ("H5_static_control", h5), ("H6_replication", h6)):
        ck(f"{k} verdict", H[k]["verdict"] == ("SUPPORTED" if ok else "NOT_SUPPORTED"))
    ck("H3 values", abs(H["H3_cost_safety_frontier"]["wrong_8"] - mean(l8, "wrong_uses")) < 0.02 and
       abs(H["H3_cost_safety_frontier"]["labels_20"] - mean(l20, "lease_labels")) < 0.02)
    ck("H4 ratio", abs(H["H4_batch_bounded"]["ratio"] -
                       mean(b5, "lease_labels") / max(1.0, mean(l8, "lease_labels"))) < 0.0002)
    verdict = ("RULE_LEASE_GOVERNANCE_SUPPORTED"
               if all((h2, h3, h4, h5, h6)) else "NOT_SUPPORTED")
    ck("verdict", verdict == rep["verdict"] == man.get("label"))
    f = rep["finding"]
    ck("finding means",
       abs(f["permanent_mean_wrong"] - mean(perm, "wrong_uses")) < 0.02 and
       abs(f["lease8_mean_wrong"] - mean(l8, "wrong_uses")) < 0.02 and
       abs(f["batch5_label_ratio"] -
           mean(b5, "lease_labels") / max(1.0, mean(l8, "lease_labels"))) < 0.0002)
    ck("static 0 false revocations", sum(r["false_revocations"] for r in static) == 0)
    ck("permanent makes no lease", all(r["lease_labels"] == 0 for r in perm))
    ck("manifest headline", man.get("headline", {}).get("verdict") == verdict and
       man.get("headline", {}).get("runs") == 432 and
       abs(man.get("headline", {}).get("lease8_mean_wrong", -1) - mean(l8, "wrong_uses")) < 0.02)

    ch = chain(allr)
    cp = json.loads((B / "checkpoints/claim_chain.json").read_text())
    ck("chain count", cp["count"] == 432, cp["count"])
    ck("chain head", cp["head"] == ch[-1]["hash"])
    ck("chain mid", cp["mid"] == ch[len(ch) // 2]["hash"])
    ck("chain recompute", sha((ch[-2]["hash"] + sha(canon(allr[-1]))).encode()) == ch[-1]["hash"])
    ck("status line", S in (B / "E331L_FINAL_REPORT.md").read_text())
    ck("limits present", len(rep.get("limits", [])) >= 6)
    ck("zero model calls", rep["resources"]["model_calls"] == 0 and
       rep["resources"]["api_spend_usd"] == 0.0)

    passed = sum(1 for x in c if x["ok"])
    out = {"schema": "cain42.e331l.verify.v1", "checks": len(c), "passed": passed,
           "failed": [x for x in c if not x["ok"]], "verdict": verdict,
           "permanent_mean_wrong": round(mean(perm, "wrong_uses"), 2),
           "lease8_mean_wrong": round(mean(l8, "wrong_uses"), 2),
           "lease8_mean_refused": round(mean(l8, "refused_uses"), 2),
           "batch5_label_ratio": round(mean(b5, "lease_labels") /
                                       max(1.0, mean(l8, "lease_labels")), 4)}
    print(json.dumps(out))
    try:
        (B.parent / "E331L_VERIFICATION_RESULTS.json").write_text(json.dumps(
            {"returncode": 0 if passed == len(c) else 1, "checks": len(c),
             "passed": passed, "output": json.dumps(out)}, indent=1))
    except OSError:
        pass
    return 0 if passed == len(c) else 1


if __name__ == "__main__":
    sys.exit(main())
