#!/usr/bin/env python3
"""E179 standalone offline verifier (stdlib + `cryptography` for Ed25519; imports no CAIN code).
usage: python3 -I verify_e179_offline.py <bundle_dir>
Checks manifest/Merkle/signature, salt commitments (revealed masters hash to the preregistered commitments), the freeze
precedes the run, and recomputes every generation's child-vs-parent paired statistics and verdict from the raw sealed rows
(rows are split into chains in run order: main, rep1, rep2, rep3), then the preregistered compounding verdict."""
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 merkle(h):
    L = sorted(h)
    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 tcdf_upper(t, df):
    x = df / (df + t * t)
    lb = math.lgamma(df / 2 + 0.5) - math.lgamma(df / 2) - math.lgamma(0.5) + (df / 2) * math.log(x) + 0.5 * math.log(1 - x) if 0 < x < 1 else 0
    ib = (math.exp(lb) * betacf(df / 2, 0.5, x) / (df / 2)) if 0 < x < (df / 2 + 1) / (df / 2 + 0.5 + 2) else (1 - math.exp(lb) * betacf(0.5, df / 2, 1 - x) / 0.5 if 0 < x < 1 else (0 if x <= 0 else 1))
    p = 0.5 * ib
    return p if t > 0 else 1 - p


def tq(df):
    lo, hi = 0.0, 50.0
    for _ in range(100):
        mid = (lo + hi) / 2
        lo, hi = (mid, hi) if tcdf_upper(mid, df) > 0.025 else (lo, mid)
    return (lo + hi) / 2


def paired(diffs):
    n = len(diffs)
    m = sum(diffs) / n
    sd = math.sqrt(sum((v - m) ** 2 for v in diffs) / (n - 1)) if n > 1 else 0.0
    if sd == 0:
        return m, (m, m), (0.0 if m > 0 else 1.0)
    se = sd / math.sqrt(n)
    h = tq(n - 1) * se
    return m, (m - h, m + h), tcdf_upper(m / se, n - 1)


def main(argv):
    B = Path(argv[1] if len(argv) > 1 else ".")
    man = json.loads((B / "E179_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")
    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"]) | {"E179_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)
    except Exception as e:  # noqa: BLE001
        check("ed25519_signature", False, type(e).__name__)
    pre = json.loads((B / "E179_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E179_PREREGISTRATION_FREEZE.json").read_text())
    masters = json.loads((B / "E179_MASTERS_REVEALED.json").read_text())
    check("salt_commitments", all(hashlib.sha256(masters[k].encode()).hexdigest() == v for k, v in pre["salt_commitments_sha256"].items()), "4 masters")
    check("preregistration_frozen", hashlib.sha256((B / "E179_PREREGISTRATION.json").read_bytes()).hexdigest() == frz["preregistration_sha256"])
    rows = [json.loads(x) for x in (B / "raw/sealed_rows.jsonl").read_text().splitlines() if x.strip()]
    chains, cur, last, lastc = [], None, None, None
    for r in rows:                      # rows are appended in run order; a new chain starts when generation or campaign index restarts
        if cur is None or r["generation"] < last or (r["generation"] == last and r["campaign"] < lastc):
            cur = {}
            chains.append(cur)
        cur.setdefault(r["generation"], []).append(r)
        last, lastc = r["generation"], r["campaign"]
    labels = ["main", "rep1", "rep2", "rep3"]
    A = json.loads((B / "E179_STATISTICAL_ANALYSIS.json").read_text())
    reached = {}
    for lab, ch in zip(labels, chains):
        chain = json.loads((B / f"raw/{lab}.json").read_text())
        n_ok = 0
        for g in sorted(ch):
            d = [r["child_q"] - r["parent_q"] for r in ch[g]]
            m, ci, p = paired(d)
            camp = {}
            for r in ch[g]:
                camp.setdefault(r["campaign"], []).append(r["child_q"] - r["parent_q"])
            cm, cci, _ = paired([sum(v) / len(v) for v in camp.values()])
            sup = m > 0 and ci[0] > 0 and p < 0.05 and cci[0] > 0
            pub = [e for e in chain if e.get("generation") == g][0]["sealed_vs_parent"]
            agree = abs(m - pub["task_level"]["mean_diff"]) < 1e-6 and sup == pub["supported"]
            check(f"{lab}_gen{g}_recomputed", agree, f"{m:+.4f} CI [{ci[0]:+.4f},{ci[1]:+.4f}] p {p:.2g} {'SUPPORTED' if sup else 'NOT SUPPORTED'}")
            if sup and n_ok == g - 1:
                n_ok = g
        reached[lab] = n_ok
    check("chains_match_analysis", reached == A["consecutive_supported_generations"], json.dumps(reached))
    h1 = reached.get("main", 0) >= 3
    h2 = sum(1 for k in ("rep1", "rep2", "rep3") if reached.get(k, 0) >= 3) >= 2
    verdict = "COMPOUNDING_SUPPORTED" if (h1 and h2) else "COMPOUNDING_NOT_ESTABLISHED"
    check("verdict_recomputed", verdict == A["verdict"], verdict)
    print(f"\n{sum(C)}/{len(C)} checks passed")
    return 0 if all(C) else 1


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