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

The engine source is withheld under the CAIN-42 IP rule. This verifier does NOT import or re-execute the
engine. It verifies the signed record: hashes/signature/Merkle, the frozen preregistration and engine
commitments, the committed-and-revealed salts, the sealed task manifests, every per-replication row,
every per-step exact McNemar comparison, the pooled Holm decision, the E183 exploratory context, and the
tamper-evident chain. Full engine re-execution is kept in the private vault and is disclosed as PARTIAL.
"""
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 = ("engine_domain.py", "engine_stack.py", "tasks.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 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 / "E184_MANIFEST.json").read_text())
    ck("status line", man.get("status") == STATUS)
    ck("confirmatory label", man.get("label") == "CONFIRMATORY" and man.get("confirmatory") is True)
    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) - {"E184_MANIFEST.json", "E184_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 / "E184_PREREGISTRATION.json").read_text())
    fr = json.loads((B / "E184_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E184_RUN_REPORT.json").read_text())
    hyp = json.loads((B / "E184_HYPOTHESIS_RESULTS.json").read_text())
    ck("prereg hash", sha((B / "E184_PREREGISTRATION.json").read_bytes()) == fr["preregistration_sha256"])
    eh = pre.get("engine_sha256", {})
    ck("engine commitments", set(eh) == {"engine_domain.py", "engine_stack.py"} and all(isinstance(v, str) and len(v) == 64 for v in eh.values()), eh)
    ck("freeze before run", fr["frozen_at"] <= rep["generated_at"], f"{fr['frozen_at']} <= {rep['generated_at']}")

    salts = json.loads((B / "E184_SALTS_REVEALED.json").read_text())["salts"]
    hashes = {k: sha(bytes.fromhex(v)) for k, v in salts.items()}
    ck("salt commitments", hashes == pre["salt_commitments_sha256"])
    ck("salt master", sha(json.dumps(hashes, sort_keys=True).encode()) == pre["salt_master_commitment_sha256"])

    sealed_doc = json.loads((B / "E184_SEALED_TASKS.json").read_text())
    for r in (1, 2, 3):
        name = f"rep{r}"
        rows = sealed_doc.get("sealed", {}).get(name, {}).get("tasks", [])
        ck(f"{name} 48 sealed tasks", len(rows) == 48, len(rows))
        ck(f"{name} 12 per concept count", all(sum(1 for t in rows if t["concept_count"] == k) == 12 for k in (1, 2, 3, 4)))
        ck(f"{name} unique uids", len({t["uid"] for t in rows}) == 48)
        canon_rows = [{"i": t["i"], "concept_count": t["concept_count"], "program": t["program"],
                       "inputs": t["inputs"], "outputs": t["outputs"], "uid": t["uid"]} for t in rows]
        ck(f"{name} task manifest", sha(json.dumps(canon_rows, sort_keys=True).encode()) == sealed_doc["sealed"][name]["sha256"])

    for r in (1, 2, 3):
        name = f"rep{r}"
        data = rep["replications"][name]
        rows = data["rows"]
        ck(f"{name} five generations", len(rows) == 5, len(rows))
        ck(f"{name} curve", [round(len(x.get("solved_uids", [])) / 48, 6) for x in rows] == data["curve"], data["curve"])
        steps = []
        for g in range(1, 5):
            st = mcnemar(rows[g].get("solved_uids", []), rows[g].get("parent_solved_uids", []))
            steps.append(st)
            recorded = data["per_step"][g - 1]
            ck(f"{name} step G{g}", st["child_only"] == recorded["child_only"] and st["parent_only"] == recorded["parent_only"]
               and abs(st["p_one_sided"] - recorded["p_one_sided"]) < 1e-15, f"{st} vs {recorded}")
        ck(f"{name} control flat", len(set(round(x, 6) for x in data["control"])) == 1, data["control"])
        ck(f"{name} retention", rows[2].get("retained") is True)
        ck(f"{name} capability count", data["capabilities_passed"] == sum(c["passed"] for c in data["capability_tests"]),
           f"{data['capabilities_passed']}/{data['capabilities_total']}")

    def pooled(i):
        b = sum(rep["replications"][n]["per_step"][i]["child_only"] for n in rep["replications"])
        c = sum(rep["replications"][n]["per_step"][i]["parent_only"] for n in rep["replications"])
        n = b + c
        p = sum(comb(n, k) for k in range(b, n + 1)) / (2 ** n) if n else 1.0
        return {"step": f"G{i+1} vs G{i}", "child_only": b, "parent_only": c, "n": n, "p_one_sided": p}

    pool = [pooled(i) for i in range(2)]
    ck("pooled G1-G0", pool[0]["child_only"] == rep["pooled_per_step"][0]["child_only"]
       and pool[0]["parent_only"] == rep["pooled_per_step"][0]["parent_only"]
       and abs(pool[0]["p_one_sided"] - rep["pooled_per_step"][0]["p_one_sided"]) < 1e-15, pool[0])
    ck("pooled G2-G1", pool[1]["child_only"] == rep["pooled_per_step"][1]["child_only"]
       and pool[1]["parent_only"] == rep["pooled_per_step"][1]["parent_only"]
       and abs(pool[1]["p_one_sided"] - rep["pooled_per_step"][1]["p_one_sided"]) < 1e-15, pool[1])
    h1 = (pool[0]["child_only"] > pool[0]["parent_only"] and pool[1]["child_only"] > pool[1]["parent_only"]
          and rep["holm"]["G1-G0"] < 0.05 and rep["holm"]["G2-G1"] < 0.05)
    ck("H1 decision consistent", (h1 and hyp["hypotheses"]["H1"]["verdict"] == "SUPPORTED" and rep["verdict"] == "COMPOUNDING_SUPPORTED")
       or ((not h1) and hyp["hypotheses"]["H1"]["verdict"] != "SUPPORTED"))
    ck("H6 disclosed partial", hyp["hypotheses"]["H6"]["verdict"] == "PARTIAL_IP_WITHHELD", hyp["hypotheses"]["H6"].get("verdict"))
    ck("errata present", (B / "E184_ERRATA.md").exists())
    led = json.loads((B / "E183_RUN_LEDGER.json").read_text())
    ck("E183 context exploratory", led.get("label") == "EXPLORATORY" and led.get("confirmatory") is False)

    chain = json.loads((B / "E184_CHAIN.json").read_text())["events"]
    prev = "0" * 64
    ok_chain = True
    for ev in chain:
        body_ev = {k: v for k, v in ev.items() if k != "hash"}
        ok_chain &= bool(ev["prev"] == prev and sha(canon(body_ev)) == ev["hash"] and body_ev.get("artifact_sha256"))
        prev = ev["hash"]
    ck("chain links", ok_chain, f"{len(chain)} events")
    ck("no AGI claim", man.get("status") == STATUS and "NOT ESTABLISHED" in rep.get("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; engine source withheld; full re-execution in the private vault"}))
    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())
