#!/usr/bin/env python3
"""E282 offline verifier — standalone, imports no CAIN code. Recomputes every headline from 1,920 rows."""
from __future__ import annotations

import hashlib
import json
import math
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
PANELS = ("honest4", "one_random4", "one_targeted4", "two_same4", "two_disjoint4")
ARMS = ("consensus4", "minimal", "full", "quorum3")
POLICIES = ("active", "random")
SALTS = ("primary", "replication")
WORLDS = 24
EX = {"E282_MANIFEST.json", "MANIFEST.json", "E282_SIGNED_BODY.json", "MERKLE_ROOT.txt", "PUBLICATION.json",
      "E282_OMEGA_SEAL.json", "E282_VERIFICATION_RESULTS.json", "E282_TAMPER_RESULTS.json"}


def canon(o):
    return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()


def sha(b):
    return hashlib.sha256(b if isinstance(b, bytes) else b.encode()).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 summarize(rows, sn):
    out = {}
    for pn in PANELS:
        for arm in ARMS:
            for pol in POLICIES:
                rs = [r for r in rows if r["salt"] == sn and r["panel"] == pn and r["arm"] == arm and r["policy"] == pol]
                labels = sum(r["labels"] for r in rs)
                out[f"{pn}|{arm}|{pol}"] = {
                    "n": len(rs), "claimed": sum(r["claimed"] for r in rs),
                    "claim_correct": sum(r["claim_correct"] for r in rs),
                    "accepted_correct": sum(1 for r in rs if r["claimed"] and r["claim_correct"] and r["accepted_protocol"]),
                    "accepted_correct_indep": sum(1 for r in rs if r["claimed"] and r["claim_correct"] and r["accepted_indep"]),
                    "accepted_false_protocol": sum(r["accepted_false_protocol"] for r in rs),
                    "accepted_false_indep": sum(r["accepted_false_indep"] for r in rs),
                    "accepted": sum(bool(r["accepted_protocol"]) for r in rs),
                    "identified": sum(1 for r in rs if r["ident_labels"]),
                    "mean_labels_identified": (sum(r["ident_labels"] for r in rs if r["ident_labels"]) /
                                               max(1, sum(1 for r in rs if r["ident_labels"]))),
                    "mean_labels_all": sum((r["ident_labels"] if r["ident_labels"] else 101) for r in rs) / len(rs),
                    "mean_queries": sum(r["queries"] for r in rs) / len(rs),
                    "mean_anchor_queries": sum(r["anchor_queries"] for r in rs) / len(rs),
                    "anchor_per_label": sum(r["anchor_queries"] for r in rs) / max(1, labels),
                    "labels_total": labels,
                    "ties": sum(r["ties"] for r in rs), "audit_ties": sum(r["audit_ties"] for r in rs),
                    "label_errors": sum(r["label_errors"] for r in rs),
                    "cap_hits": sum(r["cap_hits"] for r in rs),
                }
    return out


def labels_pair(rows, sn, pn, arm):
    a = {r["index"]: (r["ident_labels"] if r["ident_labels"] else 101)
         for r in rows if r["salt"] == sn and r["panel"] == pn and r["arm"] == arm and r["policy"] == "active"}
    b = {r["index"]: (r["ident_labels"] if r["ident_labels"] else 101)
         for r in rows if r["salt"] == sn and r["panel"] == pn and r["arm"] == arm and r["policy"] == "random"}
    wins = sum(1 for k in a if a[k] < b[k])
    losses = sum(1 for k in a if a[k] > b[k])
    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,
            "active_mean": sum(a.values()) / len(a), "random_mean": sum(b.values()) / len(b),
            "reduction": 1 - (sum(a.values()) / len(a)) / (sum(b.values()) / len(b))}


def main(bundle: Path) -> int:
    checks = []

    def ck(name, cond, detail=None):
        checks.append({"check": name, "ok": bool(cond), "detail": detail})

    pre = json.loads((bundle / "E282_PREREGISTRATION.json").read_text())
    frz = json.loads((bundle / "E282_PREREGISTRATION_FREEZE.json").read_text())
    saltf = json.loads((bundle / "E282_SALT_REVEALED.json").read_text())
    rep = json.loads((bundle / "E282_RUN_REPORT.json").read_text())
    rows = [json.loads(x) for x in (bundle / "E282_ROWS.jsonl").read_text().splitlines() if x.strip()]

    ck("preregistration_matches_freeze", sha((bundle / "E282_PREREGISTRATION.json").read_bytes()) == frz["preregistration_sha256"])
    ck("salt_commitment_matches", all(sha(saltf["salts"][k]) == pre["salt_commitment_sha256"][k] for k in SALTS)
       and all(saltf["commitment_match"].values()))
    ck("rows_1920", len(rows) == 1920, len(rows))
    ck("rows_are_24_per_cell", all(
        sum(1 for r in rows if r["salt"] == s and r["panel"] == pn and r["arm"] == a and r["policy"] == pol) == WORLDS
        for s in SALTS for pn in PANELS for a in ARMS for pol in POLICIES))
    ck("unique_episode_keys", len({(r["salt"], r["index"], r["panel"], r["arm"], r["policy"]) for r in rows}) == len(rows))

    ok_rows = True
    for r in rows:
        correct = r["claimed_mask"] is not None and r["claimed_mask"] == r["true_mask"]
        ok_rows &= (correct == r["claim_correct"])
        ok_rows &= (r["claim_wrong"] == (r["claimed"] and not correct))
        ok_rows &= (r["claimed"] == (r["claimed_mask"] is not None))
        ok_rows &= (r["accepted_false_protocol"] == (r["claimed"] and not correct and bool(r["accepted_protocol"])))
        ok_rows &= (r["accepted_false_indep"] == (r["claimed"] and not correct and bool(r["accepted_indep"])))
        if not r["claimed"]:
            ok_rows &= r["accepted_protocol"] is None and r["accepted_indep"] is None
    ck("row_fields_consistent", ok_rows)
    ck("summary_recomputed", {s: summarize(rows, s) for s in SALTS} == rep["summary"])

    p, q = rep["summary"]["primary"], rep["summary"]["replication"]
    acc = lambda cell, salt="primary": rep["summary"][salt][cell]["accepted_correct"]
    c = lambda cell, f, salt="primary": rep["summary"][salt][cell][f]
    h1 = acc("two_same4|minimal|active") >= 20
    h2 = acc("two_same4|quorum3|active") <= 6
    h3 = acc("two_same4|consensus4|active") <= 18 and (acc("two_same4|minimal|active") - acc("two_same4|consensus4|active")) >= 3
    h4 = c("two_same4|minimal|active", "anchor_per_label") <= 0.60
    h5 = acc("one_random4|consensus4|active") >= 21 and acc("one_random4|minimal|active") >= 21
    h6 = acc("two_disjoint4|consensus4|active") >= 21
    h7 = acc("honest4|consensus4|active") >= 21
    fp = sum(r["accepted_false_protocol"] for r in rows)
    h8 = fp == 0
    pairo = labels_pair(rows, "primary", "two_same4", "minimal")
    h9 = pairo["active_fewer"] >= 15 and pairo["p_one_sided"] < 0.05 and pairo["reduction"] >= 0.10
    h10 = acc("two_same4|minimal|active", "replication") >= 20 and acc("two_same4|quorum3|active", "replication") <= 6
    hyps = {"H1_minimal_anchor_recovers_collusion": h1, "H2_three_oracles_fail_collusion": h2,
            "H3_abstention_costs_acceptance": h3, "H4_anchor_is_minimal": h4,
            "H5_one_liar": h5, "H6_disjoint_collusion_is_harmless": h6,
            "H7_honest_baseline": h7, "H8_no_false_accept": h8,
            "H9_active_advantage": h9, "H10_replication": h10}
    ck("hypotheses_recomputed", all((rep["hypotheses"][k]["verdict"] == "SUPPORTED") == v for k, v in hyps.items()))
    ck("h9_statistics_recomputed", pairo == rep["hypotheses"]["H9_active_advantage"]["detail"])
    verdict = ("FOUR_ORACLE_ABSTENTION_AND_MINIMAL_ANCHOR_SUPPORTED" if all(hyps.values())
               else "PARTIAL" if (h1 and h8) else "NOT_SUPPORTED")
    ck("verdict_recomputed", rep["verdict"] == verdict, verdict)
    ck("no_false_accepts", fp == 0 and sum(r["accepted_false_indep"] for r in rows) == 0)
    ck("false_accepts_match", rep["false_accepts"] == {"protocol": fp,
                                                        "independent": sum(r["accepted_false_indep"] for r in rows)})
    ck("consensus_labels_never_false",
       all(r["label_errors"] == 0 for r in rows if r["arm"] in ("consensus4", "minimal", "full")))
    ck("quorum3_labels_can_be_false",
       any(r["label_errors"] > 0 for r in rows if r["panel"] == "two_same4" and r["arm"] == "quorum3"))
    ck("ties_only_where_expected", all(r["ties"] == 0 for r in rows if r["arm"] != "consensus4"))
    ck("status_line", rep["status"] == S and pre["status"] == S)
    ck("zero_model_calls", rep["resources"]["model_calls"] == 0 and rep["resources"]["api_spend_usd"] == 0.0)

    man_path = bundle / "E282_MANIFEST.json"
    if man_path.exists():
        man = json.loads(man_path.read_text())
        signed = (bundle / "E282_SIGNED_BODY.json").read_bytes()
        ck("signed_body_matches", canon({k: v for k, v in man.items() if k != "signature"}) == signed)
        files = sorted(x for x in bundle.rglob("*") if x.is_file() and x.name not in EX and "__pycache__" not in x.parts)
        ck("manifest_hashes", man["files"] == {str(x.relative_to(bundle)): sha(x.read_bytes()) for x in files})
        ck("merkle_root", merkle(files) == man["merkle_root"] and
           (bundle / "MERKLE_ROOT.txt").read_text().strip() == man["merkle_root"])
        ck("headline_matches_report", man["headline"]["verdict"] == rep["verdict"] and
           man["headline"]["minimal"] == acc("two_same4|minimal|active"))
        try:
            from cryptography.hazmat.primitives import serialization
            pub = bytes.fromhex(man["pubkey_ed25519"])
            pk = serialization.load_der_public_key(b"\x30\x2a\x30\x05\x06\x03\x2b\x65\x70\x03\x21\x00" + pub)
            pk.verify(bytes.fromhex(man["signature"]), signed)
            ck("signature", True)
        except Exception as e:
            ck("signature", False, str(e)[:200])

    passed = sum(1 for x in checks if x["ok"])
    out = {"schema": "cain42.e282.verification.v1", "evolution": "E282", "status": S,
           "checks": len(checks), "passed": passed, "failed": [x for x in checks if not x["ok"]],
           "verdict": rep["verdict"], "false_accepts": rep["false_accepts"],
           "headline": {"minimal": acc("two_same4|minimal|active"), "quorum3": acc("two_same4|quorum3|active"),
                        "consensus4": acc("two_same4|consensus4|active"),
                        "anchor_per_label": c("two_same4|minimal|active", "anchor_per_label"),
                        "replication_minimal": acc("two_same4|minimal|active", "replication"),
                        "one_liar": acc("one_random4|consensus4|active"),
                        "active_labels": c("two_same4|minimal|active", "mean_labels_all"),
                        "random_labels": c("two_same4|minimal|random", "mean_labels_all")}}
    print(json.dumps(out, ensure_ascii=False))
    return 0 if passed == len(checks) else 1


if __name__ == "__main__":
    sys.exit(main(Path(sys.argv[1] if len(sys.argv) > 1 else Path(__file__).resolve().parent)))
