#!/usr/bin/env python3
"""E232 standalone record verifier. No CAIN imports; engine source withheld.

Checks the signature, hashes, Merkle root, salt commitments, task integrity,
recorded programs against their tasks, paired statistics, the negative
mechanism/chain results, and the absence of overclaims.
"""
from __future__ import annotations
import hashlib
import json
import sys
from math import comb
from pathlib import Path

STATUS = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
ENGINE = {"engine.py", "run.py", "prereg.py"}


def canon(o):
    return json.dumps(o, sort_keys=True, separators=(",", ":")).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 run(seq, x, mod):
    for i in seq:
        if i == 0:
            x = tuple((v + 1) % mod for v in x)
        elif i == 1:
            x = tuple((v + 3) % mod for v in x)
        elif i == 2:
            x = tuple(v * v % mod for v in x)
        elif i == 3:
            x = tuple(v * 3 % mod for v in x)
        elif i == 4:
            s, out = 0, []
            for v in x:
                s = (s + v) % mod
                out.append(s)
            x = tuple(out)
        elif i == 5:
            x = tuple((x[j + 1] - x[j]) % mod for j in range(len(x) - 1)) if len(x) > 1 else ()
        elif i == 6:
            m, out = -1, []
            for v in x:
                m = max(m, v)
                out.append(m)
            x = tuple(out)
        elif i == 7:
            m, out = mod, []
            for v in x:
                m = min(m, v)
                out.append(m)
            x = tuple(out)
        elif i == 8:
            x = tuple(sorted(x))
        elif i == 9:
            x = x[::-1]
        elif i == 10:
            x = x[1:] + x[:1] if x else x
        elif i == 11:
            y = list(x)
            for j in range(0, len(y) - 1, 2):
                y[j], y[j + 1] = y[j + 1], y[j]
            x = tuple(y)
        else:
            raise ValueError(i)
    return x


def mc(child, parent):
    b = len(set(child) - set(parent))
    c = len(set(parent) - set(child))
    n = b + c
    p = sum(comb(n, k) for k in range(b, n + 1)) / (2 ** n) if n else 1.0
    return {"child_only": b, "parent_only": c, "n": n, "p_one_sided": p}


def holm(pairs):
    order = sorted(pairs, key=lambda x: x[1])
    out, prev = {}, 0.0
    for i, (name, p) in enumerate(order):
        a = min(1.0, max(prev, (len(order) - i) * p))
        out[name] = a
        prev = a
    return out


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

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

    man = json.loads((B / "E232_MANIFEST.json").read_text())
    ck("status", man.get("status") == STATUS)
    ck("label", man.get("label") == "CONTENT_TRANSFER_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 exist", all((B / k).exists() for k in files))
    bad = [k for k, h in files.items() if (B / k).exists() and sha((B / k).read_bytes()) != h]
    ck("hashes", not bad, bad[:3])
    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 and x.suffix != ".pyc"}
    extra = {"E232_MANIFEST.json", "E232_SIGNED_BODY.json", "E232_VERIFICATION_RESULTS.json", "PUBLICATION.json", "E232_OMEGA_SEAL.json", "E232_TAMPER_RESULTS.json"}
    unlisted = sorted(present - set(files) - extra)
    ck("no unlisted", not unlisted, unlisted[:5])
    ck("engine withheld", not any((B / n).exists() for n in ENGINE))
    ck("no secrets", not any(x.endswith((".pem", ".key", ".env", ".db")) for x in present))

    pre = json.loads((B / "E232_PREREGISTRATION.json").read_text())
    fr = json.loads((B / "E232_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E232_RUN_REPORT.json").read_text())
    hyp = json.loads((B / "E232_HYPOTHESIS_RESULTS.json").read_text())
    res = json.loads((B / "E232_RESULTS.json").read_text())
    tasks = json.loads((B / "E232_TASKS.json").read_text())
    ck("prereg hash", sha((B / "E232_PREREGISTRATION.json").read_bytes()) == fr["preregistration_sha256"])
    ck("freeze before run", fr["frozen_at"] <= rep["generated_at"])
    salts = json.loads((B / "E232_SALTS_REVEALED.json").read_text())["salts"]
    ck("salt commitments", {k: sha(bytes.fromhex(v)) for k, v in salts.items()} == pre["salt_commitments_sha256"])
    ck("salt master", sha(json.dumps({k: sha(bytes.fromhex(v)) for k, v in salts.items()}, sort_keys=True).encode()) == pre["salt_master_commitment_sha256"])

    expected = {"main": (40, 20, 101), "replication": (40, 20, 101), "third": (30, 15, 13), "reverse": (30, 15, 6)}
    resmap = {"main": "A_main", "replication": "A_replication", "third": "C_third", "reverse": "C_reverse"}
    for name, (n, sh, mod) in expected.items():
        ts = tasks["tasks"][name]
        ck(f"{name} target count", len(ts["target"]) == n and sum(t["shared"] for t in ts["target"]) == sh)
        ck(f"{name} examples", all(len(t["examples"][0]) == 5 and len(t["heldout"][0]) == 7 for t in ts["target"]))
        good = True
        for t in ts["target"]:
            prog = t["program"]
            if [list(run(prog, x, mod)) for x in t["examples"][0]] != t["examples"][1]:
                good = False
            if [list(run(prog, x, mod)) for x in t["heldout"][0]] != t["heldout"][1]:
                good = False
        ck(f"{name} hidden programs reproduce tasks", good)
        ck(f"{name} task manifest", sha(json.dumps(ts, sort_keys=True).encode()) == tasks["manifest_sha256"][name])
    # program integrity is checked from the run report (programs are stored per task)
    for name, (n, sh, mod) in expected.items():
        e = res["experiments"][resmap[name]]
        for arm in ("content", "random", "scratch", "compute", "frozen_gen1", "upper"):
            for i in e[arm]:
                t = tasks["tasks"][name]["target"][i]
                prog = rep["experiments"][resmap[name]]["arms"][{"upper": "target_dev_upper"}.get(arm, arm)]["programs"].get(str(i))
                ck(f"{name} {arm} {i} program present", prog is not None)
                if prog is not None:
                    ck(f"{name} {arm} {i} passes examples", [list(run(prog, x, mod)) for x in t["examples"][0]] == t["examples"][1])
                    ck(f"{name} {arm} {i} passes heldout", [list(run(prog, x, mod)) for x in t["heldout"][0]] == t["heldout"][1])

    def ks(name, arm):
        return set(res["experiments"][name][arm])

    main_h1 = mc(ks("A_main", "content"), ks("A_main", "random"))
    rep_h1 = mc(ks("A_replication", "content"), ks("A_replication", "random"))
    third_h1 = mc(ks("C_third", "content"), ks("C_third", "random"))
    rev_h1 = mc(ks("C_reverse", "content"), ks("C_reverse", "random"))
    hp = holm([("main", main_h1["p_one_sided"]), ("replication", rep_h1["p_one_sided"])])
    main_ok = main_h1["child_only"] > main_h1["parent_only"] and hp["main"] < 0.05
    rep_ok = rep_h1["child_only"] > rep_h1["parent_only"] and hp["replication"] < 0.05
    shared_ok = res["experiments"]["A_main"]["subsets"]["content_shared"] > res["experiments"]["A_main"]["subsets"]["random_shared"]
    verdict = "CONTENT_TRANSFER_SUPPORTED" if (main_ok and rep_ok and shared_ok) else ("CONTENT_TRANSFER_PARTIAL" if (main_ok and shared_ok) else "NOT_SUPPORTED")
    ck("main H1", main_h1 == rep["experiments"]["A_main"]["H1"])
    ck("replication H1", rep_h1 == rep["experiments"]["A_replication"]["H1"])
    ck("third H1", third_h1 == rep["experiments"]["C_third"]["H1"])
    ck("reverse H1", rev_h1 == rep["experiments"]["C_reverse"]["H1"])
    ck("holm", abs(hp["main"] - rep["hypotheses"]["H1_main_content_gt_random"]["holm"]) < 1e-15)
    ck("shared subset", res["experiments"]["A_main"]["subsets"]["content_shared"] == 13 and res["experiments"]["A_main"]["subsets"]["random_shared"] == 0)
    ck("target-only boundary", res["experiments"]["A_main"]["subsets"]["content_only"] == 0)
    ck("verdict recomputed", verdict == rep["verdict"] == hyp["verdict"])
    ck("replication direction", rep_ok)
    ck("third direction", third_h1["child_only"] > third_h1["parent_only"])
    ck("reverse direction", rev_h1["child_only"] > rev_h1["parent_only"])
    ck("compute not significant", rep["hypotheses"]["H3_main_content_gt_compute"]["verdict"] == "NOT_SUPPORTED")
    ck("depth matched", rep["fairness"]["max_primitive_depth"] == 6 and rep["fairness"]["candidate_budget"] == 60000)
    ck("memory matched", rep["fairness"]["content_macros"] == rep["fairness"]["random_macros"])
    ck("mechanism negative", rep["hypotheses"]["H11_learning_mechanism"]["verdict"] == "NOT_SUPPORTED" and rep["hypotheses"]["H11_learning_mechanism"]["delta"] == -13)
    ck("chain negative", rep["hypotheses"]["H12_recursive_chain"]["verdict"] == "PLATEAU" and rep["hypotheses"]["H12_recursive_chain"]["promotions"] == 0)
    ck("drift arms", {k: len(v["solved"]) for k, v in rep["experiments"]["D_drift"]["arms"].items()} == {"full": 1, "selective": 3, "confidence_ordered": 1, "reset": 0, "fresh": 3})

    devi = json.loads((B / "E232_DEVIATIONS.json").read_text())["deviations"]
    ck("deviation recorded", len(devi) == 1 and devi[0]["id"] == "DEVIATION-1" and devi[0]["prereg_run_py_sha256"] != devi[0]["executed_run_py_sha256"])
    rpt = (B / "E232_FINAL_REPORT.md").read_text()
    pub = (B / "E232_PUBLIC_SUMMARY.md").read_text()
    ck("report status", STATUS in rpt and "CONTENT_TRANSFER_SUPPORTED" in rpt)
    ck("negative results published", "FAILED" in rpt and "PLATEAU" in rpt and "0 promotions" in rpt)
    ck("public boundary", "shared" in pub.lower() and "not open-world" in pub.lower())

    ok = all(x["ok"] for x in checks)
    print(json.dumps({"checks": len(checks), "passed": sum(x["ok"] for x in checks), "ok": ok,
                      "verification": "E232 record; engine source withheld; tasks and programs re-checked"}))
    for x in checks:
        if not x["ok"]:
            print("FAIL", x["check"], x["detail"])
    return 0 if ok else 1


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