#!/usr/bin/env python3
"""E299 standalone verifier — stdlib + cryptography, imports no CAIN code.

Recomputes every summary and every hypothesis from the raw rows, checks the
preregistration freeze, the committed salts, the manifest signature and the
Merkle root, and re-derives the verdict. Record-level: it does not re-run the
engine (the engine source is withheld under the CAIN-42 IP rule).
"""
import hashlib
import json
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
ENG = {"world.py", "covers.py", "oracles.py", "learner.py", "pin.py", "audit.py", "run.py", "prereg.py"}
GR = ("A", "B")
PANELS = ("honest", "one_random", "one_targeted", "two_colluding", "two_coherent", "two_disjoint")
ARMS = ("PIN", "ANCHOR", "FULL", "B80", "R20")
AUDITS = ("FULL", "B80", "R20")
BENIGN = ("honest", "one_random", "one_targeted", "two_disjoint")
WORLDS = 16


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 summ(rows):
    n = len(rows)
    return {"n": n,
            "accepted": sum(1 for r in rows if r["accepted"]),
            "accepted_correct": sum(1 for r in rows if r["accepted_correct"]),
            "false_accept": sum(1 for r in rows if r["false_accept"]),
            "correct": sum(1 for r in rows if r["correct"]),
            "claim_correct": sum(1 for r in rows if r["claim_correct"]),
            "failed": sum(1 for r in rows if r.get("failed")),
            "mean_total_labels": sum(r["total_labels"] for r in rows) / n,
            "mean_audit_labels": sum(r["audit_labels"] for r in rows) / n,
            "mean_learning_labels": sum(r["learning_labels"] for r in rows) / n,
            "anchor_queries": sum(r.get("anchor_queries") or 0 for r in rows),
            "disputes": sum(r.get("disputes") or 0 for r in rows),
            "truth_in": sum(1 for r in rows if r["truth_in"])}


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 / "E299_MANIFEST.json").read_text())
    ck("status", man.get("status") == S)
    ck("label", man.get("label") in ("BYZANTINE_TRUST_BOUNDARY_MAPPED", "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:  # noqa: BLE001
        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 = {"E299_MANIFEST.json", "E299_SIGNED_BODY.json", "E299_VERIFICATION_RESULTS.json", "MANIFEST.json",
             "MERKLE_ROOT.txt", "PUBLICATION.json", "E299_OMEGA_SEAL.json", "E299_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 / "E299_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E299_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E299_RUN_REPORT.json").read_text())
    rev = json.loads((B / "E299_SALT_REVEALED.json").read_text())
    ck("prereg hash", sha((B / "E299_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 / "E299_EXTERNAL_REVIEW_STATUS.json").read_text()).get("status") == "NOT_OBTAINED")
    d = pre["design"]
    ck("design grammars", d["grammars"]["A"] == {"features": 8, "terms": 3, "literals": 3}
       and d["grammars"]["B"] == {"features": 9, "terms": 4, "literals": 3})
    ck("design panels", tuple(d["panels"]) == PANELS)
    ck("design claims", d["claims"] == 384 and d["decisions"] == 1920 and d["worlds"]["per_grammar_per_salt"] == WORLDS)
    ck("pilot disclosed", "pilot" in json.dumps(pre).lower())
    rec = rep["checkpoint"]
    cp = B / "checkpoints" / "gen0"
    ck("checkpoint chain", cp.exists() and sha((cp / "candidates.json").read_bytes()) == rec["candidates_sha256"]
       and sha((cp / "scores.json").read_bytes()) == rec["scores_sha256"])
    ch = json.loads((cp / "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"]["H8_checkpoint_resume"].get("resume") is True)
    for salt, st in rep["sets"].items():
        rows = st["rows"]
        ck(f"{salt} n", len(rows) == 960, len(rows))
        ck(f"{salt} cells", {(r["grammar"], r["panel"], r["world"], r["arm"]) for r in rows}
           == {(g, p, i, a) for g in GR for p in PANELS for i in range(WORLDS) for a in ARMS})
        ck(f"{salt} arithmetic", all(r["false_accept"] == (r["accepted"] and not r["correct"]) for r in rows)
           and all(r["accepted_correct"] == (r["accepted"] and r["correct"]) for r in rows)
           and all(r["total_labels"] >= r["learning_labels"] for r in rows))
        ck(f"{salt} pin no anchor", all((r.get("anchor_queries") or 0) == 0 for r in rows if r["arm"] == "PIN"))
        for g in GR:
            for arm in ARMS:
                k = f"{g}|{arm}"
                exp = summ([r for r in rows if r["grammar"] == g and r["arm"] == arm])
                ck(f"{salt} {k}", exp == st["summary"][k], f"{exp} vs {st['summary'][k]}")
        for p in PANELS:
            for arm in ARMS:
                k = f"panel:{p}|{arm}"
                exp = summ([r for r in rows if r["panel"] == p and r["arm"] == arm])
                ck(f"{salt} {k}", exp == st["summary"][k], f"{exp} vs {st['summary'][k]}")
    rp, rr, allr = rep["sets"]["primary"]["rows"], rep["sets"]["replication"]["rows"], (
        rep["sets"]["primary"]["rows"] + rep["sets"]["replication"]["rows"])

    def rows_of(rs, **kw):
        return [r for r in rs if all(r.get(k) == v for k, v in kw.items())]

    def benign_ok(rs):
        out = {}
        for arm in ("PIN", "ANCHOR"):
            sel = [r for r in rs if r["arm"] == arm and r["panel"] in BENIGN]
            out[arm] = {"accepted_correct": sum(r["accepted_correct"] for r in sel),
                        "false_accept": sum(r["false_accept"] for r in sel), "claims": len(sel),
                        "ok": (sum(r["accepted_correct"] for r in sel) >= 0.95 * len(sel)
                               and sum(r["false_accept"] for r in sel) == 0)}
        return out

    def collusion_ok(rs):
        sel = [r for r in rs if r["arm"] == "PIN" and r["panel"] == "two_colluding"]
        fa = sum(r["false_accept"] for r in sel)
        ac = sum(r["accepted_correct"] for r in sel)
        return {"false_accept": fa, "accepted_correct": ac, "claims": len(sel),
                "ok": fa >= 1 and ac < 0.5 * len(sel)}

    def coherent_ok(rs):
        out = {}
        for arm in ("PIN",) + AUDITS:
            sel = [r for r in rs if r["arm"] == arm and r["panel"] == "two_coherent"]
            fa = sum(r["false_accept"] for r in sel)
            out[arm] = {"false_accept": fa, "accepted_correct": sum(r["accepted_correct"] for r in sel),
                        "claims": len(sel), "ok": fa >= 0.9 * len(sel)}
        return out

    def anchor_ok(rs):
        sel = [r for r in rs if r["arm"] == "ANCHOR"]
        return {"accepted_correct": sum(r["accepted_correct"] for r in sel),
                "false_accept": sum(r["false_accept"] for r in sel), "claims": len(sel),
                "ok": (sum(r["false_accept"] for r in sel) == 0
                       and sum(r["accepted_correct"] for r in sel) >= 0.95 * len(sel))}

    b_all, c_all, coh_all, a_all = benign_ok(allr), collusion_ok(allr), coherent_ok(allr), anchor_ok(allr)
    h1 = all(v["ok"] for v in b_all.values())
    h2 = c_all["ok"]
    h3 = all(v["ok"] for v in coh_all.values())
    h4 = a_all["ok"]
    tc = [r for r in rp if r["panel"] == "two_colluding" and r["arm"] == "ANCHOR"]
    h5 = (sum(r["anchor_queries"] for r in tc) / max(1, sum(r["learning_labels"] for r in tc))) <= 0.5

    def mean_total(salt, arm, panel=None):
        rs = [r for r in rep["sets"][salt]["rows"] if r["arm"] == arm and (panel is None or r["panel"] == panel)]
        return sum(r["total_labels"] for r in rs) / len(rs)

    h6 = (mean_total("primary", "PIN", "honest") <= 0.5 * mean_total("primary", "FULL", "honest")
          and mean_total("primary", "ANCHOR", "honest") <= 1.1 * mean_total("primary", "PIN", "honest"))
    b_rep, c_rep, coh_rep, a_rep = benign_ok(rr), collusion_ok(rr), coherent_ok(rr), anchor_ok(rr)
    h7 = (all(v["ok"] for v in b_rep.values()) and c_rep["ok"]
          and all(v["ok"] for v in coh_rep.values()) and a_rep["ok"])
    H = rep["hypotheses"]

    def lab_round(x, n):
        return round(x, n)

    ck("H1 detail", all(H["H1_benign_label_sources"]["by_arm"][a][k] == b_all[a][k]
                        for a in ("PIN", "ANCHOR") for k in ("accepted_correct", "false_accept", "claims")))
    ck("H2 detail", H["H2_incoherent_collusion_breaks_soundness"]["pin_false"] == c_all["false_accept"]
       and H["H2_incoherent_collusion_breaks_soundness"]["pin_accepted_correct"] == c_all["accepted_correct"]
       and H["H2_incoherent_collusion_breaks_soundness"]["claims"] == c_all["claims"])
    ck("H3 detail", all(H["H3_coherent_collusion_defeats_label_only_verification"]["by_arm"][a]["false_accept"]
                        == coh_all[a]["false_accept"]
                        and H["H3_coherent_collusion_defeats_label_only_verification"]["by_arm"][a]["claims"]
                        == coh_all[a]["claims"] for a in ("PIN",) + AUDITS))
    ck("H4 detail", H["H4_minimal_anchor_restores_exactness"]["accepted_correct"] == a_all["accepted_correct"]
       and H["H4_minimal_anchor_restores_exactness"]["false_accept"] == a_all["false_accept"]
       and H["H4_minimal_anchor_restores_exactness"]["claims"] == a_all["claims"])
    ck("H5 detail", H["H5_anchor_is_cheap"]["anchor_per_label_twocolluding"]
       == lab_round(sum(r["anchor_queries"] for r in tc) / max(1, sum(r["learning_labels"] for r in tc)), 4))
    ck("H6 detail", H["H6_pin_efficient_honest"]["pin_mean_total"] == lab_round(mean_total("primary", "PIN", "honest"), 2)
       and H["H6_pin_efficient_honest"]["anchor_mean_total"] == lab_round(mean_total("primary", "ANCHOR", "honest"), 2)
       and H["H6_pin_efficient_honest"]["full_mean_total"] == lab_round(mean_total("primary", "FULL", "honest"), 2))
    exp = {"H1_benign_label_sources": h1, "H2_incoherent_collusion_breaks_soundness": h2,
           "H3_coherent_collusion_defeats_label_only_verification": h3,
           "H4_minimal_anchor_restores_exactness": h4, "H5_anchor_is_cheap": h5,
           "H6_pin_efficient_honest": h6, "H7_replication": h7,
           "H8_checkpoint_resume": H["H8_checkpoint_resume"].get("resume") is True}
    for k, ok in exp.items():
        if k.startswith("H2") or k.startswith("H3"):
            want = "LIMIT_CONFIRMED" if ok else "NOT_CONFIRMED"
        else:
            want = "SUPPORTED" if ok else "NOT_SUPPORTED"
        ck(f"{k} verdict", H[k]["verdict"] == want, f"{H[k]['verdict']} vs {want}")
    verdict = "BYZANTINE_TRUST_BOUNDARY_MAPPED" if all(exp.values()) else "NOT_SUPPORTED"
    ck("verdict", verdict == rep["verdict"] == man["label"], f"{verdict} vs {rep['verdict']}")
    ck("decisions", len(allr) == 1920)
    ck("claims", len([r for r in allr if r["arm"] == "PIN"]) == 384)
    ck("headline", man.get("headline", {}).get("pin_false") == sum(1 for r in allr if r["arm"] == "PIN" and r["false_accept"])
       and man.get("headline", {}).get("anchor_accepted_correct") == a_all["accepted_correct"])
    ck("coherent limit is reported", man.get("headline", {}).get("coherent_pin_false")
       == coh_all["PIN"]["false_accept"] and coh_all["PIN"]["false_accept"] >= 1)
    passed = sum(1 for x in c if x["ok"])
    print(json.dumps({"schema": "cain42.e299.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())
