#!/usr/bin/env python3
"""Standalone E183 record verifier.

E183 is EXPLORATORY. The engine source is withheld under the CAIN-42 IP rule; this verifier checks the signed
record, both runs, the per-step nulls, the 12-feature audit, the freeze-order disclosure and the errata.
"""
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_FILES = ("domain.py", "stack.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 mcnemar(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 run_steps(run):
    rows = run["rows"]
    return [mcnemar(rows[g].get("solved_uids", []), rows[g].get("parent_solved_uids", [])) for g in range(1, len(rows))]


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 / "E183_MANIFEST.json").read_text())
    ck("status line", man.get("status") == STATUS)
    ck("exploratory label", man.get("label") == "EXPLORATORY" and man.get("confirmatory") is False)
    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:  # noqa: BLE001
        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"}
    unlisted = sorted(present - set(files) - {"E183_MANIFEST.json", "E183_VERIFICATION_RESULTS.json", "PUBLICATION.json"})
    ck("no unlisted file", not unlisted, unlisted[:5])
    ck("engine source withheld", not any((B / n).exists() for n in ENGINE_FILES),
       [n for n in ENGINE_FILES if (B / n).exists()])

    pre = json.loads((B / "E183_PREREGISTRATION.json").read_text())
    fr = json.loads((B / "E183_PREREGISTRATION_FREEZE.json").read_text())
    hyp = json.loads((B / "E183_HYPOTHESIS_RESULTS.json").read_text())
    led = json.loads((B / "E183_RUN_LEDGER.json").read_text())
    ck("prereg hash", sha((B / "E183_PREREGISTRATION.json").read_bytes()) == fr["preregistration_sha256"])
    ck("ledger exploratory", led.get("label") == "EXPLORATORY" and led.get("confirmatory") is False and len(led.get("runs", [])) == 2)
    ck("hypotheses not confirmatory", hyp.get("confirmatory") is False)
    ck("freeze order disclosed", led.get("freeze_order", {}).get("freeze_at", "") >= led.get("freeze_order", {}).get("results_at", ""),
       led.get("freeze_order"))

    run_a = json.loads((B / "E183_RUN_A_12.json").read_text())
    run_b = json.loads((B / "E183_STACK_REPORT.json").read_text())
    per = json.loads((B / "E183_PER_STEP.json").read_text())
    ck("run A 12 tasks", run_a.get("sealed_tasks") == 12 and len(run_a["rows"]) == 5)
    ck("run B 24 tasks", run_b.get("sealed_tasks") == 24 and len(run_b["rows"]) == 5)
    ck("run A curve", [round(len(x.get("solved_uids", [])) / 12, 6) for x in run_a["rows"]] == run_a["curve"])
    ck("run B curve", [round(len(x.get("solved_uids", [])) / 24, 6) for x in run_b["rows"]] == run_b["curve"])
    for label, run in (("A", run_a), ("B", run_b)):
        st = run_steps(run)
        rec = per[f"run_{label}"]["per_step"]
        ck(f"run {label} per-step", all(st[i]["child_only"] == rec[i]["child_only"] and st[i]["parent_only"] == rec[i]["parent_only"]
                                        and abs(st[i]["p_one_sided"] - rec[i]["p_one_sided"]) < 1e-15 for i in range(len(st))), st)
        ck(f"run {label} no significant step", all(x["p_one_sided"] >= 0.05 for x in st))
        ck(f"run {label} cumulative", abs(run["cumulative_g2_vs_g0"]["p_one_sided"] - mcnemar(run["rows"][2]["solved_uids"], run["rows"][0]["solved_uids"])["p_one_sided"]) < 1e-15)
    cap = json.loads((B / "E183_CAPABILITY_MATRIX.json").read_text())
    c04 = [c for c in cap["tests"] if c["id"] == "C04"][0]
    c01 = [c for c in cap["tests"] if c["id"] == "C01"][0]
    ck("capabilities 11/12", cap.get("passed") == 11 and cap.get("total") == 12)
    ck("diagnosis is the gap", c01["passed"] is False, c01.get("detail"))
    ck("task count 24", "24" in c04.get("detail", ""), c04.get("detail"))
    ck("errata present", (B / "E183_ERRATA.md").exists())
    st = json.loads((B / "E183_CONFIRMATORY_STATUS.json").read_text())
    ck("E183-C not run", st.get("status") == "SUPERSEDED_NOT_RUN")
    ck("no AGI claim", man.get("status") == STATUS)
    pub = B / "PUBLICATION.json"
    if pub.exists():
        pj = json.loads(pub.read_text())
        ck("publication merkle", pj.get("merkle_root") == man.get("merkle_root"))
        ck("four surfaces", len(pj.get("surfaces", {})) == 4, len(pj.get("surfaces", {})))
    else:
        ck("pre-publication", True)
    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": "record-level; exploratory; engine source withheld"}))
    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())
