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

Recomputes the summary table, the five hypotheses and the superorganism name rule from the 384 raw
episodes, and checks the manifest, signature, Merkle root, preregistration freeze, salts and chain.
"""
from __future__ import annotations

import hashlib
import json
import math
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
SALTS = ("primary", "replication")
PANELS = ("honest", "one_random")
ARMS = ("single", "majority")
POLICIES = ("active", "random")
WORLDS = 24
EX = {"E356_MANIFEST.json", "E356_SIGNED_BODY.json", "E356_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E356_OMEGA_SEAL.json",
      "E356_TAMPER_RESULTS.json"}
LEAK = {"run.py", "learner.py", "oracles.py", "world.py", "verify.py"}


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


def sha(b):
    return hashlib.sha256(b if isinstance(b, bytes) else b.encode()).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 count(rows, salt, panel_name, arm):
    rs = [r for r in rows if r["salt"] == salt and r["panel"] == panel_name and r["arm"] == arm]
    return {"n": len(rs), "verified": sum(1 for r in rs if r["verified"]),
            "accepted": sum(1 for r in rs if r["accepted"]),
            "mean_queries": round(sum(r["queries"] for r in rs) / len(rs), 2) if rs else None}


def pairs(rows, salt):
    b = c = 0
    for i in range(WORLDS):
        for pol in POLICIES:
            mr = [r for r in rows if r["salt"] == salt and r["panel"] == "one_random"
                  and r["index"] == i and r["policy"] == pol]
            m = next(x for x in mr if x["arm"] == "majority")
            sg = next(x for x in mr if x["arm"] == "single")
            if m["verified"] and not sg["verified"]:
                b += 1
            if sg["verified"] and not m["verified"]:
                c += 1
    n = b + c
    return {"b_colony_only": b, "c_single_only": c, "n_discordant": n,
            "p_one_sided": (sum(math.comb(n, k) for k in range(b, n + 1)) / (2 ** n)) if n else 1.0}


def decide(rows):
    summary = {sn: {pn: {arm: count(rows, sn, pn, arm) for arm in ARMS} for pn in PANELS}
               for sn in SALTS}
    p = summary["primary"]["one_random"]
    q = summary["replication"]["one_random"]
    hp = summary["primary"]["honest"]
    hq = summary["replication"]["honest"]
    mp, mq = pairs(rows, "primary"), pairs(rows, "replication")
    name_ok = (p["majority"]["verified"] >= 30 and p["single"]["verified"] <= 6
               and p["majority"]["verified"] - p["single"]["verified"] >= 24
               and mp["p_one_sided"] < 1e-6
               and hp["majority"]["verified"] >= 35 and hp["majority"]["verified"] >= hp["single"]["verified"] - 2
               and q["majority"]["verified"] >= 25 and q["single"]["verified"] <= 8
               and q["majority"]["verified"] > q["single"]["verified"]
               and hq["majority"]["verified"] >= 35 and hq["majority"]["verified"] >= hq["single"]["verified"] - 2)
    H = {
        "H1_collective_beats_single_under_a_liar": {
            "verdict": "SUPPORTED" if (p["majority"]["verified"] >= 30 and p["single"]["verified"] <= 6
                                       and p["majority"]["verified"] - p["single"]["verified"] >= 24
                                       and mp["p_one_sided"] < 1e-6) else "NOT_SUPPORTED",
            "detail": "primary: colony >=30/48, single <=6/48, difference >=24, exact McNemar p < 1e-6"},
        "H2_honest_non_inferiority": {
            "verdict": "SUPPORTED" if (hp["majority"]["verified"] >= 35
                                       and hp["majority"]["verified"] >= hp["single"]["verified"] - 2
                                       and hq["majority"]["verified"] >= 35
                                       and hq["majority"]["verified"] >= hq["single"]["verified"] - 2) else "NOT_SUPPORTED",
            "detail": "with honest oracles the colony is non-inferior to the single (within 2/48) and >=35/48 on both salts"},
        "H3_replication": {
            "verdict": "SUPPORTED" if (q["majority"]["verified"] >= 25 and q["single"]["verified"] <= 8
                                       and q["majority"]["verified"] > q["single"]["verified"]) else "NOT_SUPPORTED",
            "detail": "replication salt: colony >=25/48, single <=8/48 and colony > single"},
        "H4_equal_budget": {"verdict": "SUPPORTED" if 300 >= 3 * 100 else "NOT_SUPPORTED",
                            "detail": "the single arm's row budget (300) is at least the colony's potential reads (100 x 3)"},
        "H5_external_review": {"verdict": "BLOCKED", "detail": "external review NOT OBTAINED"},
    }
    verdict = "SUPERORGANISM_NAME_SUPPORTED" if name_ok else "NOT_SUPPORTED"
    return summary, H, verdict, mp, mq, name_ok


def chain_ok(ch):
    prev = "0" * 64
    for i, x in enumerate(ch):
        if x["i"] != i or x["prev"] != prev:
            return False
        prev = x["hash"]
    return True


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

    def ck(name, cond):
        checks.append((name, bool(cond)))

    man = json.loads((d / "E356_MANIFEST.json").read_text())
    pre = json.loads((d / "E356_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E356_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((d / "E356_RUN_REPORT.json").read_text())
    salt = json.loads((d / "E356_SALT_REVEALED.json").read_text())
    acc = json.loads((d / "E356_ACCEPTANCE_REGISTRY.json").read_text())
    dev = json.loads((d / "E356_DEVIATIONS.json").read_text())
    ext = json.loads((d / "E356_EXTERNAL_REVIEW_STATUS.json").read_text())
    report_md = (d / "E356_FINAL_REPORT.md").read_text()

    ck("manifest schema", man.get("schema") == "cain42.e356.manifest.v1")
    ck("evolution", man.get("evolution") == "E356" and rep.get("evolution") == "E356")
    ck("status", man.get("status") == S and rep.get("status") == S)
    files = sorted(p for p in d.rglob("*") if p.is_file()
                   and str(p.relative_to(d)) not in EX and "__pycache__" not in p.parts)
    ck("manifest files", set(man["files"]) == {str(p.relative_to(d)) for p in files})
    ck("manifest hashes", all(sha(p.read_bytes()) == man["files"][str(p.relative_to(d))] for p in files))
    ck("merkle", man["merkle_root"] == merkle(files))
    ck("merkle file", (d / "MERKLE_ROOT.txt").read_text().strip() == man["merkle_root"])

    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    body = json.loads((d / "E356_SIGNED_BODY.json").read_text())
    pub = Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"]))
    pub.verify(bytes.fromhex(man["signature"]), canon(body))
    ck("signature", True)
    ck("signed body binds merkle", body["merkle_root"] == man["merkle_root"])

    ck("prereg freeze", sha((d / "E356_PREREGISTRATION.json").read_bytes())
       == frz["preregistration_sha256"] == rep["preregistration_sha256"])
    ck("freeze precedes run", frz["frozen_at"] <= rep["generated_at"])
    ck("salt commitments", all(sha(bytes.fromhex(v)) == pre["salt_commitment_sha256"][k]
                               for k, v in salt["salts"].items()))
    ck("salt revealed after run", salt["revealed_at"] >= rep["generated_at"])

    leak = [p.name for p in d.rglob("*") if p.is_file() and p.name in LEAK]
    ck("source withheld", not leak)
    ck("no engine leak text", not any("from cain.cain2027" in p.read_text(errors="ignore")
                                      for p in d.rglob("*.py") if p.name != "verify_e356_offline.py"))

    rows = rep["sets"]["primary"]["rows"] + rep["sets"]["replication"]["rows"]
    ck("episodes", len(rows) == 384)
    ck("episode grid", all(sum(1 for r in rows if r["salt"] == sn and r["panel"] == pn
                              and r["arm"] == a) == 48
                           for sn in SALTS for pn in PANELS for a in ARMS))
    summary, H, verdict, mp, mq, name_ok = decide(rows)
    ck("summary", summary == rep["summaries"])
    ck("verdict", verdict == rep["verdict"])
    ck("name rule", name_ok == rep["finding"]["name_rule_ok"]
       and rep["name_rule_outcome"] == ("superorganism (candidate)" if name_ok else "AGI-RSI research organism"))
    ck("hypotheses", all(H[k]["verdict"] == rep["hypotheses"][k]["verdict"] for k in H))
    ck("mcnemar", mp == rep["finding"]["mcnemar_primary"] and mq == rep["finding"]["mcnemar_replication"])
    ck("finding counts", all(rep["finding"][k] == v for k, v in {
        "primary_one_random": summary["primary"]["one_random"],
        "replication_one_random": summary["replication"]["one_random"],
        "primary_honest": summary["primary"]["honest"],
        "replication_honest": summary["replication"]["honest"]}.items()))
    ck("report verdict", f"**Preregistered verdict: {rep['verdict']}.**" in report_md)
    ck("acceptance", acc["verdict"] == rep["verdict"])
    ck("external", ext["status"] == "NOT_OBTAINED")
    ck("deviations", isinstance(dev.get("deviations"), list)
       and all(set(x) >= {"id", "text"} for x in dev["deviations"]))
    ck("resources", rep["resources"]["model_calls"] == 0 and rep["resources"]["api_spend_usd"] == 0.0)
    ch = [json.loads(l) for l in (d / "checkpoints/claim_chain.jsonl").read_text().splitlines()]
    compact = [json.loads(x) for x in [json.dumps(r, sort_keys=True) for r in rows]]
    ck("row chain length", len(ch) == len(rows))
    recomputed = []
    prev = "0" * 64
    for r in compact:
        hh = sha((prev + sha(json.dumps(r, sort_keys=True, separators=(",", ":")))).encode())
        recomputed.append(hh)
        prev = hh
    ck("row chain values", [x["hash"] for x in ch] == recomputed)
    ck("checkpoint", rep["checkpoint"]["head"] == recomputed[-1])
    ck("chain links", chain_ok(ch))
    cp = json.loads((d / "checkpoints/claim_chain.json").read_text())
    ck("chain file", cp["count"] == len(ch) and cp["head"] == recomputed[-1])
    ck("finding multiple", rep["finding"]["majority_vs_single_multiple"] ==
       (round(summary["primary"]["one_random"]["majority"]["verified"] /
              summary["primary"]["one_random"]["single"]["verified"], 4)
        if summary["primary"]["one_random"]["single"]["verified"] else None))
    ck("public summary", rep["verdict"] in (d / "E356_PUBLIC_SUMMARY.md").read_text())
    hl = man.get("headline") or {}
    ck("headline", hl.get("name_rule_ok") == name_ok and hl.get("episodes") == 384
       and hl.get("worlds") == 24)
    bad = [n for n, ok in checks if not ok]
    for n, ok in checks:
        print(("PASS " if ok else "FAIL ") + n)
    print(f"{len(checks) - len(bad)}/{len(checks)} checks passed")
    return 0 if not bad else 1


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