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

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

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
STRATEGIES = ("static", "audit_target", "all_rows")
ARMS = ("consensus4", "minimal_honest", "minimal_bad", "minimal_q3")
POLICIES = ("active", "random")
SALTS = ("primary", "replication")
WORLDS = 24
EX = {"E287_MANIFEST.json", "MANIFEST.json", "E287_SIGNED_BODY.json", "MERKLE_ROOT.txt", "PUBLICATION.json",
      "E287_OMEGA_SEAL.json", "E287_VERIFICATION_RESULTS.json", "E287_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):
    return 1.0 if n == 0 else sum(math.comb(n, k) for k in range(b, n + 1)) / (2 ** n)


def summarize(rows, sn):
    out = {}
    for st in STRATEGIES:
        for arm in ARMS:
            for pol in POLICIES:
                rs = [r for r in rows if r["salt"] == sn and r["strategy"] == st and r["arm"] == arm and r["policy"] == pol]
                labels = sum(r["labels"] for r in rs)
                out[f"{st}|{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_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),
                    "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, st, arm):
    a = {r["index"]: (r["ident_labels"] if r["ident_labels"] else 101)
         for r in rows if r["salt"] == sn and r["strategy"] == st 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["strategy"] == st 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 / "E287_PREREGISTRATION.json").read_text())
    frz = json.loads((bundle / "E287_PREREGISTRATION_FREEZE.json").read_text())
    saltf = json.loads((bundle / "E287_SALT_REVEALED.json").read_text())
    rep = json.loads((bundle / "E287_RUN_REPORT.json").read_text())
    rows = [json.loads(x) for x in (bundle / "E287_ROWS.jsonl").read_text().splitlines() if x.strip()]

    ck("preregistration_matches_freeze", sha((bundle / "E287_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_1152", len(rows) == 1152, len(rows))
    ck("rows_are_24_per_cell", all(
        sum(1 for r in rows if r["salt"] == s and r["strategy"] == st and r["arm"] == a and r["policy"] == pol) == WORLDS
        for s in SALTS for st in STRATEGIES for a in ARMS for pol in POLICIES))
    ck("unique_episode_keys", len({(r["salt"], r["index"], r["strategy"], r["arm"], r["policy"]) for r in rows}) == len(rows))

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

    acc = lambda cell, salt="primary": rep["summary"][salt][cell]["accepted_correct"]
    h1 = acc("static|consensus4|active") >= 18
    h2 = acc("audit_target|consensus4|active") <= 3
    h3 = acc("audit_target|minimal_honest|active") >= 20
    h4 = acc("all_rows|minimal_honest|active") >= 18
    fp = sum(r["accepted_false_protocol"] for r in rows)
    h5 = fp == 0
    h6 = acc("static|minimal_bad|active") <= 2 and acc("all_rows|minimal_bad|active") <= 2
    h7 = acc("static|minimal_q3|active") >= 18 and acc("all_rows|minimal_q3|active") >= 18
    h8 = acc("static|minimal_q3|active") >= 18
    pairo = labels_pair(rows, "primary", "static", "minimal_q3")
    h9 = pairo["active_fewer"] >= 15 and pairo["p_one_sided"] < 0.05 and pairo["reduction"] >= 0.10
    h10 = (acc("audit_target|consensus4|active", "replication") <= 3
           and acc("all_rows|minimal_q3|active", "replication") >= 18)
    hyps = {"H1_static_baseline": h1, "H2_late_collusion_suppresses_proof": h2, "H3_honest_anchor_restores_proof": h3,
            "H4_total_collusion": h4, "H5_no_false_accept": h5, "H6_single_anchor_is_a_denial_point": h6,
            "H7_anchor_quorum_restores_liveness": h7, "H8_quorum_under_static_collusion": 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 = ("ADAPTIVE_COLLUSION_DENIES_PROOF_NOT_TRUTH_SUPPORTED" if all(hyps.values())
               else "PARTIAL" if h5 and (h2 or h7) else "NOT_SUPPORTED")
    ck("verdict_recomputed", rep["verdict"] == verdict, verdict)
    ck("false_accepts_match", rep["false_accepts"] == {"protocol": fp,
                                                        "independent": sum(r["accepted_false_indep"] for r in rows)})
    ck("honest_arms_never_label_false",
       all(r["label_errors"] == 0 for r in rows if r["arm"] in ("consensus4", "minimal_honest", "minimal_q3")))
    ck("audit_target_learning_is_clean",
       all(r["ties"] == 0 for r in rows if r["strategy"] == "audit_target"))
    ck("all_rows_consensus4_never_claims",
       all(not r["claimed"] for r in rows if r["strategy"] == "all_rows" and r["arm"] == "consensus4"))
    ck("bad_anchor_corrupts_labels",
       any(r["label_errors"] > 0 for r in rows if r["strategy"] == "all_rows" and r["arm"] == "minimal_bad"))
    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 / "E287_MANIFEST.json"
    if man_path.exists():
        man = json.loads(man_path.read_text())
        signed = (bundle / "E287_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"]["q3_all_rows"] == acc("all_rows|minimal_q3|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.e287.verification.v1", "evolution": "E287", "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": {"late_collusion_consensus": acc("audit_target|consensus4|active"),
                        "late_collusion_honest_anchor": acc("audit_target|minimal_honest|active"),
                        "bad_anchor_static": acc("static|minimal_bad|active"),
                        "q3_static": acc("static|minimal_q3|active"),
                        "q3_all_rows": acc("all_rows|minimal_q3|active"),
                        "q3_all_rows_replication": acc("all_rows|minimal_q3|active", "replication"),
                        "anchor_per_label_q3": rep["summary"]["primary"]["static|minimal_q3|active"]["anchor_per_label"],
                        "active_labels": rep["summary"]["primary"]["static|minimal_q3|active"]["mean_labels_all"],
                        "random_labels": rep["summary"]["primary"]["static|minimal_q3|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)))
