#!/usr/bin/env python3
"""E271 offline verifier. Recomputes the headline from per-world rows; imports no CAIN code."""
import hashlib
import json
import math
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
ENG = {"world.py", "active.py", "run.py", "prereg.py"}


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 binom_sf(b, n):
    if n == 0:
        return 1.0
    return sum(math.comb(n, k) for k in range(b, n + 1)) / (2 ** n)


def sign_test(a, b):
    wins = sum(1 for x, y in zip(a, b) if x < y)
    losses = sum(1 for x, y in zip(a, b) if x > y)
    return {"active_fewer": wins, "random_fewer": losses, "ties": len(a) - wins - losses,
            "p_one_sided": binom_sf(wins, wins + losses) if wins + losses else 1.0}


def mcnemar(a, b):
    oa = sum(1 for x, y in zip(a, b) if x and not y)
    ob = sum(1 for x, y in zip(a, b) if y and not x)
    return {"active_only": oa, "random_only": ob, "p_one_sided": binom_sf(oa, oa + ob) if oa + ob else 1.0}


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 / "E271_MANIFEST.json").read_text())
    ck("status", man.get("status") == S)
    ck("label", man.get("label") in ("ACTIVE_STRUCTURE_IDENTIFICATION_SUPPORTED", "NOT_SUPPORTED"))
    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", all((B / k).exists() for k in files))
    ck("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}
    extra = {"E271_MANIFEST.json", "E271_SIGNED_BODY.json", "E271_VERIFICATION_RESULTS.json", "MANIFEST.json",
             "MERKLE_ROOT.txt", "PUBLICATION.json", "E271_OMEGA_SEAL.json", "E271_TAMPER_RESULTS.json"}
    ck("no unlisted", not (present - set(files) - extra), sorted(present - set(files) - extra)[:5])
    ck("code withheld", not any((B / n).exists() for n in ENG))

    pre = json.loads((B / "E271_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E271_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E271_RUN_REPORT.json").read_text())
    rev = json.loads((B / "E271_SALT_REVEALED.json").read_text())
    ck("prereg hash", sha((B / "E271_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 / "E271_EXTERNAL_REVIEW_STATUS.json").read_text()).get("status") == "NOT_OBTAINED")

    rec = rep["checkpoint"]
    d = B / "checkpoints" / "gen0"
    ck("checkpoint chain", d.exists() and sha((d / "candidates.json").read_bytes()) == rec["candidates_sha256"]
       and sha((d / "scores.json").read_bytes()) == rec["scores_sha256"])
    ch = json.loads((d / "chain.json").read_text())
    ck("checkpoint hash", sha(json.dumps({k: v for k, v in ch.items() if k != "hash"}, sort_keys=True).encode()) == ch["hash"])
    ck("resume", rep["hypotheses"]["H6_checkpoint_resume"].get("resume") is True)

    for name, st in rep["sets"].items():
        rows = st["rows"]
        ck(f"{name} n", len(rows) == 48, len(rows))
        for arm in ("active", "random"):
            sm = st["summary"][arm]
            ex = sum(1 for r in rows if r[arm]["identified"])
            b48 = sum(1 for r in rows if r[arm]["identified_by_48"])
            mq = sum(r[arm]["queries"] for r in rows) / len(rows)
            caps = sum(r[arm]["cap_hits"] for r in rows)
            ck(f"{name} {arm} identified", ex == sm["identified"], f"{ex} vs {sm['identified']}")
            ck(f"{name} {arm} by48", b48 == sm["identified_by_48"], f"{b48} vs {sm['identified_by_48']}")
            ck(f"{name} {arm} mean", abs(mq - sm["mean_queries"]) < 1e-12)
            ck(f"{name} {arm} caps", caps == sm["cap_hits"], f"{caps} vs {sm['cap_hits']}")

    p = rep["sets"]["primary"]
    rp = rep["sets"]["replication"]
    pa, pr = p["summary"]["active"], p["summary"]["random"]
    ra, rr = rp["summary"]["active"], rp["summary"]["random"]
    st = sign_test([r["active"]["queries"] for r in p["rows"]], [r["random"]["queries"] for r in p["rows"]])
    st_r = sign_test([r["active"]["queries"] for r in rp["rows"]], [r["random"]["queries"] for r in rp["rows"]])
    red = 1 - pa["mean_queries"] / pr["mean_queries"]
    red_r = 1 - ra["mean_queries"] / rr["mean_queries"]
    h5 = mcnemar([r["active"]["identified_by_48"] for r in p["rows"]], [r["random"]["identified_by_48"] for r in p["rows"]])
    H = rep["hypotheses"]
    ck("H2 sign", H["H2_fewer_labels"]["sign_test"] == st, st)
    ck("H3 sign", H["H3_replication"]["sign_test"] == st_r, st_r)
    ck("H5 mcnemar", H["H5_budget_48"]["mcnemar"] == h5, h5)
    h1 = pa["identified"] >= 44
    h2 = red >= 0.20 and st["active_fewer"] > st["random_fewer"] and st["p_one_sided"] < 0.01
    h3 = ra["identified"] >= 44 and red_r >= 0.20 and st_r["p_one_sided"] < 0.01
    cap_total = pa["cap_hits"] + pr["cap_hits"] + ra["cap_hits"] + rr["cap_hits"]
    exact_ok = all((not r["active"]["identified"] or r["active"]["exact_at_end"])
                   and (not r["random"]["identified"] or r["random"]["exact_at_end"])
                   for st_ in rep["sets"].values() for r in st_["rows"])
    h4 = cap_total == 0 and exact_ok
    h5ok = h5["active_only"] > h5["random_only"] and h5["p_one_sided"] < 0.05
    h6 = H["H6_checkpoint_resume"].get("resume") is True
    exp = {"H1_active_identifies": h1, "H2_fewer_labels": h2, "H3_replication": h3,
           "H4_exactness": h4, "H5_budget_48": h5ok, "H6_checkpoint_resume": h6}
    for k, ok in exp.items():
        want = "SUPPORTED" if ok else "NOT_SUPPORTED"
        ck(f"{k} verdict", H[k]["verdict"] == want, f'{H[k]["verdict"]} vs {want}')
    verdict = "ACTIVE_STRUCTURE_IDENTIFICATION_SUPPORTED" if all(exp.values()) else "NOT_SUPPORTED"
    ck("verdict", verdict == rep["verdict"] == man["label"], f'{verdict} vs {rep["verdict"]}')

    passed = sum(1 for x in c if x["ok"])
    print(json.dumps({"schema": "cain42.e271.verify.v1", "checks": len(c), "passed": passed,
                      "failed": [x for x in c if not x["ok"]], "verdict": verdict}, ensure_ascii=False))
    return 0 if passed == len(c) else 1


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