#!/usr/bin/env python3
"""E281 offline verifier — standalone, imports no CAIN code.

Recomputes every headline number from the 1,152 per-episode rows and checks the
signed record, the salt commitment, the audit outcome and the verdict.

Usage: python3 verify_e281_offline.py [bundle_dir]
"""
from __future__ import annotations

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

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
PANELS = ("honest", "one_random", "one_targeted", "two_colluding")
ARMS = ("single", "majority", "agree2")
POLICIES = ("active", "random")
SALTS = ("primary", "replication")
WORLDS = 24
EX = {"E281_MANIFEST.json", "MANIFEST.json", "E281_SIGNED_BODY.json", "MERKLE_ROOT.txt",
      "PUBLICATION.json", "E281_OMEGA_SEAL.json", "E281_VERIFICATION_RESULTS.json",
      "E281_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, salt):
    cells = {}
    for pn in PANELS:
        for arm in ARMS:
            for pol in POLICIES:
                rs = [r for r in rows if r["salt"] == salt and r["panel"] == pn and r["arm"] == arm and r["policy"] == pol]
                cells[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_panel": sum(r["accepted_true_panel"] for r in rs),
                    "accepted_correct_indep": sum(r["accepted_true_indep"] for r in rs),
                    "accepted_false_panel": sum(r["accepted_false_panel"] for r in rs),
                    "accepted_false_indep": sum(r["accepted_false_indep"] for r in rs),
                    "accepted": sum(bool(r["accepted_panel"]) for r in rs),
                    "mean_labels_all": sum((r["ident_labels"] if r["ident_labels"] else 101) for r in rs) / len(rs),
                    "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"]))),
                    "identified": sum(1 for r in rs if r["ident_labels"]),
                    "mean_queries": sum(r["queries"] for r in rs) / len(rs),
                    "label_errors": sum(r["label_errors"] for r in rs),
                    "cap_hits": sum(r["cap_hits"] for r in rs),
                    "inconsistent_steps": sum(r["inconsistent_steps"] for r in rs),
                }
    return cells


def labels_pair(rows, salt, pn, arm):
    a = {r["index"]: (r["ident_labels"] if r["ident_labels"] else 101)
         for r in rows if r["salt"] == salt 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"] == salt 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])
    ties = len(a) - wins - losses
    return {"active_fewer": wins, "random_fewer": losses, "ties": ties,
            "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 / "E281_PREREGISTRATION.json").read_text())
    frz = json.loads((bundle / "E281_PREREGISTRATION_FREEZE.json").read_text())
    saltf = json.loads((bundle / "E281_SALT_REVEALED.json").read_text())
    rep = json.loads((bundle / "E281_RUN_REPORT.json").read_text())
    rows = [json.loads(x) for x in (bundle / "E281_ROWS.jsonl").read_text().splitlines() if x.strip()]

    ck("preregistration_matches_freeze", sha((bundle / "E281_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["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))

    # per-row internal consistency
    ok_rows = True
    for r in rows:
        correct = r["claimed_mask"] is not None and r["claimed_mask"] == r["true_mask"]
        if correct != r["claim_correct"]:
            ok_rows = False
        if r["claim_wrong"] != (r["claimed"] and not correct):
            ok_rows = False
        if r["claimed"] != (r["claimed_mask"] is not None):
            ok_rows = False
        if r["claimed"] is None and (r["accepted_panel"] is not None or r["accepted_indep"] is not None):
            ok_rows = False
        if r["accepted_false_indep"] != (r["claimed"] and not correct and bool(r["accepted_indep"])):
            ok_rows = False
        if r["accepted_false_panel"] != (r["claimed"] and not correct and bool(r["accepted_panel"])):
            ok_rows = False
    ck("row_fields_consistent", ok_rows)

    summary = {s: summarize(rows, s) for s in SALTS}
    ck("summary_recomputed", summary == rep["summary"])

    p, q = summary["primary"], summary["replication"]
    h1 = (p["one_random|single|active"]["accepted_correct_indep"] <= 3 and
          p["one_random|majority|active"]["accepted_correct_indep"] >= 18)
    h2 = p["one_targeted|majority|active"]["accepted_correct_indep"] >= 18
    h3 = p["two_colluding|majority|active"]["accepted_correct_indep"] <= 6
    false_indep = sum(r["accepted_false_indep"] for r in rows)
    false_panel = sum(r["accepted_false_panel"] for r in rows)
    h4 = false_indep == 0
    h5 = p["honest|majority|active"]["accepted_correct_indep"] >= 20
    pairo = labels_pair(rows, "primary", "one_random", "majority")
    h6 = pairo["active_fewer"] >= 15 and pairo["p_one_sided"] < 0.05 and pairo["reduction"] >= 0.10
    h7 = (q["one_random|single|active"]["accepted_correct_indep"] <= 3 and
          q["one_random|majority|active"]["accepted_correct_indep"] >= 18)
    h8 = p["two_colluding|agree2|active"]["accepted_correct_indep"] <= 6
    hyps = {
        "H1_single_lone_liar_collapses": h1, "H2_targeted_liar": h2,
        "H3_two_colluders_defeat_quorum": h3, "H4_no_false_accept": h4,
        "H5_honest_baseline": h5, "H6_active_advantage_survives": h6,
        "H7_replication": h7, "H8_agree2_shortcut": h8,
    }
    ck("hypotheses_recomputed",
       all((rep["hypotheses"][k]["verdict"] == "SUPPORTED") == v for k, v in hyps.items()))
    ck("h6_statistics_recomputed", pairo == rep["hypotheses"]["H6_active_advantage_survives"]["detail"])
    verdict = ("BYZANTINE_ORACLE_IDENTIFICATION_SUPPORTED" if all(hyps.values())
               else "PARTIAL" if (h1 and h4) else "NOT_SUPPORTED")
    ck("verdict_recomputed", rep["verdict"] == verdict, verdict)
    ck("no_false_accepts", false_indep == 0 and false_panel == 0, {"indep": false_indep, "panel": false_panel})
    ck("false_accepts_match", rep["false_accepts"] == {"independent": false_indep, "panel": false_panel})
    ck("label_errors_only_in_lying_arms",
       all(r["label_errors"] == 0 for r in rows if r["panel"] == "honest"))
    ck("no_claims_accepted_under_collusion",
       all(r["accepted_false_indep"] is False for r in rows if r["panel"] == "two_colluding"))
    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)

    # signed record (when the manifest is present)
    man_path = bundle / "E281_MANIFEST.json"
    if man_path.exists():
        man = json.loads(man_path.read_text())
        signed = (bundle / "E281_SIGNED_BODY.json").read_bytes()
        body = {k: v for k, v in man.items() if k != "signature"}
        ck("signed_body_matches", canon(body) == 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"]["majority_accepted_correct"] == p["one_random|majority|active"]["accepted_correct_indep"])
        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:  # pragma: no cover
            ck("signature", False, str(e)[:200])

    passed = sum(1 for c in checks if c["ok"])
    out = {"schema": "cain42.e281.verification.v1", "evolution": "E281", "status": S,
           "checks": len(checks), "passed": passed, "failed": [c for c in checks if not c["ok"]],
           "verdict": rep["verdict"], "false_accepts": {"independent": false_indep, "panel": false_panel},
           "headline": {"majority_accepted_correct_primary": p["one_random|majority|active"]["accepted_correct_indep"],
                        "single_accepted_correct_primary": p["one_random|single|active"]["accepted_correct_indep"],
                        "majority_accepted_correct_replication": q["one_random|majority|active"]["accepted_correct_indep"],
                        "colluding_majority_accepted_correct": p["two_colluding|majority|active"]["accepted_correct_indep"],
                        "active_labels": p["one_random|majority|active"]["mean_labels_all"],
                        "random_labels": p["one_random|majority|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)))
