#!/usr/bin/env python3
"""E170 standalone offline verifier (standard library; `cryptography` only for Ed25519). Imports no CAIN code.

usage: python3 -I verify_e170_offline.py <bundle_dir>
Checks: manifest hashes + Merkle + signature; no research source; preregistration precedes the run; salts match their
commitments; theta* is exactly the policy the recorded meta-search selected (no hand-picking); every meta-test and
replication row rescored from the published answer key; compute neutrality (every theta used <= K dev evaluations);
H1/H2/H5 statistics, Holm and verdict rules recomputed.
"""
import hashlib
import json
import math
import sys
from pathlib import Path

C = []


def check(n, ok, d=""):
    C.append(bool(ok))
    print(("PASS " if ok else "FAIL ") + n + (f"  [{d}]" if d else ""))


def jl(p):
    return [json.loads(x) for x in Path(p).read_text().splitlines() if x.strip()]


def merkle(h):
    L = sorted(h)
    while len(L) > 1:
        if len(L) % 2:
            L.append(L[-1])
        L = [hashlib.sha256((L[i] + L[i + 1]).encode()).hexdigest() for i in range(0, len(L), 2)]
    return L[0] if L else hashlib.sha256(b"").hexdigest()


def betacf(a, b, x):
    qab, qap, qam, c, d = a + b, a + 1, a - 1, 1.0, 1 - (a + b) * x / (a + 1)
    d = 1 / (d if abs(d) > 1e-300 else 1e-300)
    h = d
    for m in range(1, 300):
        m2 = 2 * m
        for aa in (m * (b - m) * x / ((qam + m2) * (a + m2)), -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))):
            d = 1 + aa * d
            d = 1 / (d if abs(d) > 1e-300 else 1e-300)
            c = 1 + aa / c
            c = c if abs(c) > 1e-300 else 1e-300
            h *= d * c
    return h


def ibeta(a, b, x):
    if x <= 0:
        return 0.0
    if x >= 1:
        return 1.0
    lb = math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log(1 - x)
    return math.exp(lb) * betacf(a, b, x) / a if x < (a + 1) / (a + b + 2) else 1 - math.exp(lb) * betacf(b, a, 1 - x) / b


def paired(a, b):
    d = [x - y for x, y in zip(a, b)]
    n = len(d)
    if n < 2:
        return {"n": n, "mean": 0.0, "p": 1.0, "lo": 0.0, "hi": 0.0}
    m = sum(d) / n
    sd = math.sqrt(sum((x - m) ** 2 for x in d) / (n - 1))
    se = sd / math.sqrt(n)
    if sd > 0:
        t = m / se
        x = (n - 1) / (n - 1 + t * t)
        p = 0.5 * ibeta((n - 1) / 2, 0.5, x)
        p = p if t > 0 else 1 - p
    else:
        p = 0.0 if m > 0 else 1.0
    return {"n": n, "mean": m, "p": p, "lo": m - 1.96 * se, "hi": m + 1.96 * se}


def per_task(rows, arm, reps=None):
    by = {}
    for r in rows:
        if r["arm"] == arm and (reps is None or r["rep"] in reps):
            by.setdefault((r["campaign"], r["uid"]), []).append(r["quality"])
    return {k: sum(v) / len(v) for k, v in by.items()}


def cmp(rows, a, b, reps=None):
    pa, pb = per_task(rows, a, reps), per_task(rows, b, reps)
    ks = sorted(set(pa) & set(pb))
    return paired([pa[k] for k in ks], [pb[k] for k in ks])


def quality(key, choice):
    if not key or choice not in key["names"]:
        return 0.0
    j = key["names"].index(choice)
    return 0.0 if j in set(key["forbidden"]) else float(key["h"][j])


def main(argv):
    B = Path(argv[1] if len(argv) > 1 else ".")
    man = json.loads((B / "E170_MANIFEST.json").read_text())
    bad = [f for f, h in man["files"].items() if not (B / f).exists() or hashlib.sha256((B / f).read_bytes()).hexdigest() != h]
    check("manifest_file_hashes", not bad, f"{len(man['files'])} files, {len(bad)} mismatched")
    extra = [str(p.relative_to(B)) for p in B.rglob("*") if p.is_file() and str(p.relative_to(B)) not in set(man["files"]) | {"E170_MANIFEST.json", "PUBLICATION.json"}]
    check("no_unlisted_files", not extra, ",".join(extra[:3]))
    check("merkle_root", merkle(list(man["files"].values())) == man["merkle_root"])
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        body = {k: v for k, v in man.items() if k != "signature"}
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(man["signature"]), json.dumps(body, sort_keys=True, separators=(",", ":")).encode())
        check("ed25519_signature", True, man["pubkey_fingerprint"])
    except Exception as e:  # noqa: BLE001
        check("ed25519_signature", False, type(e).__name__)
    leaks = [f for f in man["files"] if not f.endswith(".py") and any(s in (B / f).read_text(errors="ignore") for s in ("def select(problem", "def decide(problem", "def episode(lab"))]
    leaks += [f for f in man["files"] if f.endswith(".py") and f != "verify_e170_offline.py"]
    check("no_research_source_published", not leaks, ",".join(leaks[:3]))
    pre = json.loads((B / "E170_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E170_PREREGISTRATION_FREEZE.json").read_text())
    check("preregistration_hash", hashlib.sha256((B / "E170_PREREGISTRATION.json").read_bytes()).hexdigest() == frz["preregistration_sha256"])
    sc, sr = json.loads((B / "E170_SALT_COMMITMENT.json").read_text()), json.loads((B / "E170_SALT_REVEALED.json").read_text())
    check("salt_matches_commitment", hashlib.sha256(sr["master"].encode()).hexdigest() == sc["master_sha256"] and sc["committed_at"] >= frz["frozen_at"])
    fc, fr = json.loads((B / "E170_FRESH_SALT_COMMITMENT.json").read_text()), json.loads((B / "E170_FRESH_SALT_REVEALED.json").read_text())
    check("fresh_salt_matches_commitment", hashlib.sha256(fr["fresh_master"].encode()).hexdigest() == fc["fresh_master_sha256"])
    ms = json.loads((B / "raw/meta_search.json").read_text())
    cand = [h for h in ms["history"] if h["role"] in ("theta0", "mutant")]
    best = max(cand, key=lambda h: h["meta_dev_gain"])
    rounds_ok = all(h["meta_dev_gain"] <= ms["theta_star_meta_dev_gain"] + 1e-12 for h in cand)
    check("theta_star_is_the_selected_policy", rounds_ok and abs(best["meta_dev_gain"] - ms["theta_star_meta_dev_gain"]) < 1e-12,
          f"theta* meta-dev {ms['theta_star_meta_dev_gain']:+.4f}, theta0 {ms['theta0_meta_dev_gain']:+.4f}, {len(cand)} policies scored")
    key = json.loads((B / "keys/answer_key.json").read_text())
    rows = jl(B / "raw/meta_test/rows.jsonl")
    rep = jl(B / "raw/replication/rows.jsonl")
    mism = [r for r in rows + rep if abs(quality(key.get(r["task_uid"]), r["choice"]) - r["quality"]) > 1e-6]
    check("rows_rescored_from_answer_key", rows and rep and not mism, f"{len(rows)} meta-test + {len(rep)} replication rows, {len(mism)} mismatches")
    over = [r for r in rows + rep if r["used"] > r["budget"] or r["budget"] != 16]
    check("oracle_budget_respected", not over, f"{len(over)} violations")
    eps = jl(B / "raw/meta_test/episodes.jsonl") + jl(B / "raw/replication/episodes.jsonl")
    dev_ok = all(e[a]["record"]["dev_evaluations"] <= 8 for e in eps for a in ("theta0", "theta_star", "theta_random"))
    check("compute_neutrality", dev_ok, "every episode <= 8 dev candidate evaluations")
    A = json.loads((B / "E170_STATISTICAL_ANALYSIS.json").read_text())
    H = A["hypotheses"]
    for k, (a, b, rs) in {"H1": ("theta_star", "theta0", rows), "H2": ("theta_star", "theta_random", rows), "H5": ("theta_star", "theta0", rep)}.items():
        t = cmp(rs, a, b)
        p = H[k]
        check(f"recomputed_{k}", abs(t["mean"] - p["mean_diff"]) < 1e-5 and t["n"] == p["n"] and (abs(t["p"] - p["p_one_sided"]) < 1e-4 or (t["p"] < 1e-12 and p["p_one_sided"] < 1e-12)),
              f"{t['mean']:+.5f} n {t['n']} p {t['p']:.3g}")
    raw_p = A["raw_p"]
    items = sorted((v, k) for k, v in raw_p.items() if v is not None)
    run, ok = 0.0, True
    for i, (v, k) in enumerate(items):
        run = max(run, min(1.0, (len(items) - i) * v))
        ok &= abs(run - A["holm"][k]) < 1e-6
    check("holm_recomputed", ok)
    print(f"\n{sum(C)}/{len(C)} checks passed")
    return 0 if all(C) else 1


if __name__ == "__main__":
    sys.exit(main(sys.argv))
