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

usage: python3 -I verify_e167_offline.py <bundle_dir>

It recomputes the results from raw rows and the published answer key (a second implementation of the scoring and of
the statistics, written separately from the experiment code but by the same team):
  integrity    manifest file hashes, Merkle root, Ed25519 signature, no research source in the bundle
  timeline     preregistration hash and freeze precede the sealed run; salt reveals match their commitments
  rescoring    every sealed / adversarial / fresh row's quality recomputed from choice + key
  accounting   every row's evaluations within its arm's preregistered budget; no duplicate units; sealed tasks disjoint
               from diagnosis tasks
  statistics   paired differences, one-sided Student t p-values (own incomplete-beta), Holm, verdict rules for H2/H6
  structure    arm-collapse detection for memory/collective; MCPGate decision-log hash chain; gate matrix consistency
"""
import hashlib
import json
import math
import sys
from pathlib import Path

C = []


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


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


def merkle(hexes):
    L = sorted(hexes)
    if not L:
        return hashlib.sha256(b"").hexdigest()
    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]


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 t_sf(t, df):
    x = df / (df + t * t)
    p = 0.5 * ibeta(df / 2, 0.5, x)
    return p if t > 0 else 1 - p


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


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


def per_task(rows, arm, reps=None, domains=None):
    by = {}
    for r in rows:
        if r["arm"] == arm and (reps is None or r["rep"] in reps) and (domains is None or r["domain"] in domains):
            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, domains=None, campaigns=None):
    if campaigns is not None:
        rows = [r for r in rows if r["campaign"] in campaigns]
    pa, pb = per_task(rows, a, reps, domains), per_task(rows, b, reps, domains)
    ks = sorted(set(pa) & set(pb))
    return paired([pa[k] for k in ks], [pb[k] for k in ks])


def holm(p):
    items = sorted((v, k) for k, v in p.items() if v is not None)
    m, run, out = len(items), 0.0, {}
    for i, (v, k) in enumerate(items):
        run = max(run, min(1.0, (m - i) * v))
        out[k] = run
    return out


def main(argv):
    B = Path(argv[1] if len(argv) > 1 else ".")
    man = json.loads((B / "E167_MANIFEST.json").read_text())
    # ------------------------------------------------------------------ integrity
    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")
    listed = set(man["files"]) | {"E167_MANIFEST.json", "PUBLICATION.json"}   # PUBLICATION.json: live record written after signing
    extra = [str(p.relative_to(B)) for p in B.rglob("*") if p.is_file() and str(p.relative_to(B)) not in listed]
    check("no_unlisted_files", not extra, ",".join(extra[:3]))
    check("merkle_root", merkle(list(man["files"].values())) == man["merkle_root"], man["merkle_root"][:16])
    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 ImportError:
        check("ed25519_signature", False, "cryptography not installed")
    except Exception as e:  # noqa: BLE001
        check("ed25519_signature", False, type(e).__name__)
    leaks = []
    for f in man["files"]:
        if f.endswith("verify_e167_offline.py"):
            continue
        t = (B / f).read_text(errors="ignore") if (B / f).stat().st_size < 50_000_000 else ""
        if "def select(problem" in t or "def decide(problem" in t or "def normalize(s)" in t:
            leaks.append(f)
    check("no_research_source_published", not leaks, ",".join(leaks[:3]))
    # ------------------------------------------------------------------ timeline
    pre = json.loads((B / "E167_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E167_PREREGISTRATION_FREEZE.json").read_text())
    check("preregistration_hash", hashlib.sha256((B / "E167_PREREGISTRATION.json").read_bytes()).hexdigest() == frz["preregistration_sha256"] == man["preregistration_sha256"])
    recs = [json.loads(p.read_text()) for p in sorted(B.glob("raw/campaign_*/record.json"))]
    first = min(r["started_at"] for r in recs)
    check("preregistration_before_sealed_run", frz["frozen_at"] < first, f"{frz['frozen_at']} < {first}")
    sc = json.loads((B / "E167_SALT_COMMITMENT.json").read_text())
    sr = json.loads((B / "E167_SALT_REVEALED.json").read_text())
    check("sealed_salt_matches_commitment", hashlib.sha256(sr["sealed_master"].encode()).hexdigest() == sc["sealed_master_sha256"]
          and sc["committed_at"] < first)
    fr_ok = True
    if (B / "E167_FRESH_SALT_COMMITMENT.json").exists() and (B / "E167_FRESH_SALT_REVEALED.json").exists():
        fc = json.loads((B / "E167_FRESH_SALT_COMMITMENT.json").read_text())
        fv = json.loads((B / "E167_FRESH_SALT_REVEALED.json").read_text())
        fr_ok = hashlib.sha256(fv["fresh_master"].encode()).hexdigest() == fc["fresh_master_sha256"]
    check("fresh_salt_matches_commitment", fr_ok)
    # ------------------------------------------------------------------ rescoring
    key = json.loads((B / "keys/answer_key.json").read_text())
    rows = [r for p in sorted(B.glob("raw/campaign_*/sealed.jsonl")) for r in jl(p)]
    mism = [r for r in rows if abs(quality(key.get(r["task_uid"], {}), r["choice"]) - r["quality"]) > 1e-6]
    check("sealed_rows_rescored", rows and not mism, f"{len(rows)} rows, {len(mism)} mismatches")
    adv = [r for p in sorted(B.glob("raw/campaign_*/adversarial.jsonl")) for r in jl(p)]
    akey = json.loads((B / "keys/adversarial_key.json").read_text())
    am = [r for r in adv if r.get("choice") is not None and abs(quality(akey.get(f"{r['uid']}|{r['variant']}", {}), r["choice"]) - r["quality"]) > 1e-6]
    check("adversarial_rows_rescored", adv and not am, f"{len(adv)} rows, {len(am)} mismatches")
    ret = []
    fresh = [r for q in sorted(B.glob("raw/fresh/campaign_*/sealed.jsonl")) for r in jl(q)]
    fm = [r for r in fresh if abs(quality(key.get(r["task_uid"], {}), r["choice"]) - r["quality"]) > 1e-6]
    check("fresh_rows_rescored", fresh and not fm, f"{len(fresh)} rows, {len(fm)} mismatches")
    # ------------------------------------------------------------------ accounting
    budgets = pre["budgets"]
    over = [r for r in rows + fresh + ret if r["used"] > r["budget"]]
    wrong_b = [r for r in rows if r["budget"] != (budgets["search"] if r["arm"] == "P_search" else budgets["standard"])]
    check("compute_within_budget", not over and not wrong_b, f"{len(over)} over budget, {len(wrong_b)} wrong budget")
    units = [(r["campaign"], r["uid"], r["rep"], r["arm"]) for r in rows]
    check("no_duplicate_units", len(units) == len(set(units)), f"{len(units)} units")
    diag = {r["uid"] for p in sorted(B.glob("raw/campaign_*/diagnosis_train.jsonl")) for r in jl(p)}
    sealed_uids = {r["uid"] for r in rows}
    check("sealed_disjoint_from_diagnosis", not (sealed_uids & diag), f"{len(sealed_uids)} sealed, {len(diag)} diagnosis tasks")
    per_c = {}
    for r in rows:
        per_c.setdefault(r["uid"], set()).add(r["campaign"])
    check("sealed_tasks_unique_per_campaign", all(len(v) == 1 for v in per_c.values()))
    # ------------------------------------------------------------------ statistics
    A = json.loads((B / "E167_STATISTICAL_ANALYSIS.json").read_text())
    Hh = A["hypotheses"]
    blind = tuple(pre["groups"]["blind"])
    fonly = tuple(r for r in blind if r.startswith("F"))
    tests = {"H1": (cmp(rows, "P3_hybrid", "P2_lib", reps=blind), Hh["H1"]["P3_hybrid_minus_P2_lib_blind"]),
             "H2": (cmp(rows, "P3_hybrid", "P_search"), Hh["H2"]["P3_hybrid_minus_P_search"]),
             "H3": (cmp(rows, "P3_write", "P2_lib", reps=blind), Hh["H3"]["P3_write_minus_P2_lib_blind"]),
             "H9": (cmp(rows, "P3_hybrid", "P2_lib", reps=fonly), Hh["H9"]["P3_hybrid_minus_P2_lib_family_F"])}
    for k, (t, p) in tests.items():
        if p.get("n", 0) < 2:
            check(f"recomputed_{k}", t["n"] < 2 or t["mean_diff"] == 0, "not testable (identical arms)")
            continue
        ok = abs(t["mean_diff"] - 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))
        check(f"recomputed_{k}", ok, f"diff {t['mean_diff']:+.6f} n {t['n']} p {t['p']:.3g}")
    hol = holm(A["raw_p"])
    check("holm_recomputed", all(abs(hol[k] - A["holm"][k]) < 1e-6 for k in hol), f"{len(hol)} tests")
    led = [json.loads(x) for x in (B / "E167_API_LEDGER.jsonl").read_text().splitlines() if x.strip()]
    spent = sum(x.get("usd", 0) for x in led if x["event"] == "settle")
    check("api_spend_within_ceiling", spent <= pre["api"]["ceiling_usd"] + 1e-9, f"${spent:.4f} of ${pre['api']['ceiling_usd']}")
    chain_ok, n = True, 0
    prev = "0" * 64
    for line in (B / "raw/mcpgate_log.jsonl").read_text().splitlines():
        rec = json.loads(line)
        h = rec.pop("hash")
        chain_ok &= rec["prev"] == prev and hashlib.sha256(json.dumps(rec, sort_keys=True).encode()).hexdigest() == h
        prev = h
        n += 1
    check("mcpgate_decision_chain", chain_ok and n > 0, f"{n} records")
    hyp = json.loads((B / "E167_HYPOTHESIS_REGISTER.json").read_text())
    check("hypothesis_register_matches_analysis", all(hyp["verdicts"].get(k) == v for k, v in A["verdicts"].items()))
    print(f"\n{sum(C)}/{len(C)} checks passed")
    return 0 if all(C) else 1


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