#!/usr/bin/env python3
"""Standalone offline verifier for the CAIN-42 E149 evidence bundle.

Python standard library only. Imports no CAIN code and no third-party package (Ed25519 is verified with the
RFC 8032 reference algorithm below). Statistics are re-implemented here, independently of analyze_e149.py.

    python3 -I verify_e149_offline.py <bundle_dir>

Passing means the bundle is internally consistent and the published numbers follow from the signed raw rows.
It does not prove the scientific claim is true, and it cannot re-generate tasks (that needs the agent code);
the byte-for-byte reproduction from the revealed salt is a separate signed record (reproduction.json).
"""
import hashlib
import json
import math
import statistics as st
import sys
from pathlib import Path

# ---------- Ed25519 verification (RFC 8032 §6 reference, verify only) ----------
_p = 2 ** 255 - 19
_q = 2 ** 252 + 27742317777372353535851937790883648493
_d = -121665 * pow(121666, _p - 2, _p) % _p
_I = pow(2, (_p - 1) // 4, _p)


def _inv(x):
    return pow(x, _p - 2, _p)


def _xrecover(y):
    xx = (y * y - 1) * _inv(_d * y * y + 1)
    x = pow(xx, (_p + 3) // 8, _p)
    if (x * x - xx) % _p:
        x = x * _I % _p
    return _p - x if x % 2 else x


_By = 4 * _inv(5) % _p
_B = (_xrecover(_By), _By, 1, _xrecover(_By) * _By % _p)


def _add(P, Q):
    A = (P[1] - P[0]) * (Q[1] - Q[0]) % _p
    B = (P[1] + P[0]) * (Q[1] + Q[0]) % _p
    C = 2 * P[3] * Q[3] * _d % _p
    D = 2 * P[2] * Q[2] % _p
    E, F, G, H = B - A, D - C, D + C, B + A
    return (E * F % _p, G * H % _p, F * G % _p, E * H % _p)


def _mul(s, P):
    Q = (0, 1, 1, 0)
    while s:
        if s & 1:
            Q = _add(Q, P)
        P, s = _add(P, P), s >> 1
    return Q


def _eq(P, Q):
    return (P[0] * Q[2] - Q[0] * P[2]) % _p == 0 and (P[1] * Q[2] - Q[1] * P[2]) % _p == 0


def _decode(b):
    y = int.from_bytes(b, "little") & ((1 << 255) - 1)
    if y >= _p:
        raise ValueError
    x = _xrecover(y)
    if (x & 1) != (b[31] >> 7):
        x = _p - x
    P = (x, y, 1, x * y % _p)
    if (-x * x + y * y - 1 - _d * x * x * y * y) % _p:
        raise ValueError
    return P


def ed25519_verify(pub_hex, msg, sig_hex):
    try:
        pk, sig = bytes.fromhex(pub_hex), bytes.fromhex(sig_hex)
        A, R = _decode(pk), _decode(sig[:32])
        s = int.from_bytes(sig[32:], "little")
        if s >= _q:
            return False
        h = int.from_bytes(hashlib.sha512(sig[:32] + pk + msg).digest(), "little") % _q
        return _eq(_mul(s, _B), _add(R, _mul(h, A)))
    except Exception:
        return False


# ---------- statistics (independent re-implementation) ----------
def canon(o):
    return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=True, default=float)


def sha(b):
    return hashlib.sha256(b).hexdigest()


def sign_tail(w, l):
    n = w + l
    return sum(math.comb(n, k) for k in range(w, n + 1)) / 2 ** n if n else 1.0


def t975(df):
    # Hill (1970) inverse-t approximation; accurate to ~1e-6 for df >= 3
    a = 1 / (df - 0.5); b = 48 / a ** 2; c = ((20700 * a / b - 98) * a - 16) * a + 96.36
    dd = ((94.5 / (b + c) - 3) / b + 1) * math.sqrt(a * math.pi / 2) * df
    x = dd * 0.05; y = x ** (2 / df)
    if y > 0.05 + a:
        z = -1.959963985; y = z * z
        c = (((0.05 * dd * z - 5) * y - 7) * y - 2) * y + b + c
        y = (((((0.4 * y + 6.3) * y + 36) * y + 94.5) / c - y - 3) / b + 1) * z
        y = a * y * y; y = math.expm1(y)
    else:
        y = ((1 / (((df + 6) / (df * y) - 0.089 * dd - 0.822) * (df + 2) * 3) + 0.5 / (df + 4)) * y - 1) * (df + 1) / (df + 2) + 1 / y
    return math.sqrt(df * y)


def stats(d):
    n, m = len(d), st.mean(d)
    se = st.stdev(d) / math.sqrt(n)
    w, l = sum(x > 0 for x in d), sum(x < 0 for x in d)
    return {"n": n, "mean": m, "lo": m - t975(n - 1) * se, "w": w, "l": l, "t": n - w - l, "p": sign_tail(w, l), "prev": sign_tail(l, w)}


def holm(ps):
    o = sorted(range(len(ps)), key=lambda i: ps[i]); adj = [0.0] * len(ps); run = 0.0
    for r, i in enumerate(o):
        run = max(run, min(1.0, (len(ps) - r) * ps[i])); adj[i] = run
    return adj


CHECKS = []


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


def main():
    B = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    J = lambda n: json.loads((B / n).read_text())
    man = J("MANIFEST.json")
    files = man["files"]
    bad = [f for f, h in files.items() if not (B / f).is_file() or sha((B / f).read_bytes()) != h]
    check("manifest: every listed file present with matching SHA-256", not bad, f"{len(files)} files" + (f"; bad {bad[:3]}" if bad else ""))
    body = canon({k: v for k, v in man.items() if k != "signature"}).encode()
    check("manifest Ed25519 signature (bundle key)", ed25519_verify(man["bundle_pubkey_ed25519"], body, man["signature"]))
    merkle = (B / "MERKLE_ROOT.txt").read_text().strip()
    leaves = [bytes.fromhex(sha((f + ":" + files[f]).encode())) for f in sorted(files)]
    while len(leaves) > 1:
        leaves = [hashlib.sha256(leaves[i] + (leaves[i + 1] if i + 1 < len(leaves) else leaves[i])).digest() for i in range(0, len(leaves), 2)]
    check("Merkle root recomputed from manifest", leaves[0].hex() == merkle == man["merkle_root"], merkle[:16])

    pre = J("preregistration.json")
    check("preregistration hash recomputes", sha(canon({k: v for k, v in pre.items() if k != "preregistration_hash"}).encode()) == pre["preregistration_hash"], pre["preregistration_hash"][:16])
    pc = J("prereg_commit.json")
    com, run = J("raw/salt_commitment.json"), J("raw/run.json")
    check("preregistration committed before salt existed (G3)", pc["commit_time_utc"] < com["committed_at"], f"{pc['commit_time_utc']} < {com['committed_at']}")
    salt = bytes.fromhex(run["salt_hex_revealed_after_signing"])
    check("salt commitment matches revealed salt (G5)", sha(salt) == com["salt_sha256"] == run["salt_sha256"])
    check("run bound to this preregistration", run["preregistration_hash"] == com["preregistration_hash"] == pre["preregistration_hash"])
    raw = (B / "raw/blocks.jsonl").read_bytes()
    check("blocks.jsonl hash matches signed run record", sha(raw) == run["blocks_sha256"])
    check("run record Ed25519 signature (evaluator key)", ed25519_verify(run["evaluator_pubkey_ed25519"], canon({k: v for k, v in run.items() if k != "signature"}).encode(), run["signature"]))
    rows = [json.loads(x) for x in raw.decode().splitlines()]
    nsig = sum(ed25519_verify(run["evaluator_pubkey_ed25519"], canon({k: v for k, v in r.items() if k != "signature"}).encode(), r["signature"]) for r in rows)
    check("every block record signed by the evaluator", nsig == len(rows), f"{nsig}/{len(rows)}")
    K, KH = pre["design"]["K_PRIMARY"], pre["design"]["K_HELDOUT"]
    P = sorted((r for r in rows if r["tag"] == "e149-primary"), key=lambda r: r["block"])
    H = sorted((r for r in rows if r["tag"] == "e149-heldout"), key=lambda r: r["block"])
    check("no missing or duplicate blocks", [r["block"] for r in P] == list(range(K)) and [r["block"] for r in H] == list(range(KH)), f"{len(P)}+{len(H)}")
    check("equal compute per decision (hypothesis evals = 32 x |H| x queries)", all(
        a["hyp_evals_total"] % 32 == 0 for r in rows for a in r["arms"].values()))
    check("per-task rows reproduce block aggregates", all(
        a["verified_discoveries"] == sum(t[0] for t in a["per_task"]) and a["queries_total"] == sum(t[1] for t in a["per_task"]) for r in rows for a in r["arms"].values()))

    an, g, snap = J("analysis.json"), J("gates.json"), J("e149-snapshot.json")
    v = lambda r, a: r["arms"][a]["verified_discoveries"]
    s = stats([v(r, "candidate") - v(r, "parent") for r in P])
    verdict = ("REPLICATION_SUPPORTED" if s["p"] < 0.05 and s["lo"] > 0 else
               "REPLICATION_NOT_SUPPORTED" if s["mean"] <= 0 or s["prev"] < 0.05 else "REPLICATION_INCONCLUSIVE")
    ar = an["track_a"]["result"]
    check("primary recomputed: mean, W/L/T, sign p, CI", abs(s["mean"] - ar["mean"]) < 1e-6 and (s["w"], s["l"], s["t"]) == (ar["wins"], ar["losses"], ar["ties"])
          and abs(s["p"] - ar["sign_p_one_sided"]) < 1e-12 and abs(s["lo"] - ar["ci95_t"][0]) < 1e-3,
          f"mean {s['mean']:+.4f}, {s['w']}/{s['l']}/{s['t']}, p {s['p']:.3g}, CI low {s['lo']:+.3f}")
    check("replication verdict follows the preregistered rule", verdict == an["track_a"]["verdict"] == snap["track_a"]["verdict"], verdict)
    e = lambda r, a: r["arms"][a]["efficiency_mean"]
    s1 = stats([e(r, "candidate") - e(r, "parent") for r in P])
    check("S1 cost-aware reward mean recomputed", abs(s1["mean"] - an["track_a"]["secondary"]["S1_cost_aware_reward"]["mean"]) < 1e-6, f"{s1['mean']:+.5f}")
    hs = stats([v(r, "candidate") - v(r, "parent") for r in H])
    hv = "NON_INFERIOR" if hs["lo"] > -0.8 else "NON_INFERIORITY_NOT_DEMONSTRATED"
    check("held-out non-inferiority recomputed", hv == an["track_a"]["held_out"]["verdict"], f"{hs['mean']:+.3f}, CI low {hs['lo']:+.3f}")
    ms = {a: stats([v(r, a) - v(r, "parent") for r in P]) for a in ("p_stop", "p_temper", "p_both")}
    adj = holm([ms[a]["p"] for a in ("p_stop", "p_temper", "p_both")])
    sig = {a: p < 0.05 and ms[a]["lo"] > 0 for a, p in zip(("p_stop", "p_temper", "p_both"), adj)}
    mv = ("STOPPING_AND_TEMPERING" if sig["p_stop"] and sig["p_temper"] else "STOPPING_THRESHOLD" if sig["p_stop"] else
          "TEMPERING" if sig["p_temper"] else "INTERACTION" if sig["p_both"] else "MECHANISM_UNRESOLVED")
    check("mechanism verdict follows the preregistered rule", mv == an["track_d"]["verdict"] == snap["track_d"]["verdict"], mv)
    rp = J("reproduction.json")
    rrep = (B / "raw/reproduction_blocks.jsonl").read_bytes()
    unsig = lambda b: [{k: v for k, v in json.loads(x).items() if k != "signature"} for x in b.decode().splitlines()]
    same_bytes, same_content = sha(rrep) == run["blocks_sha256"], unsig(rrep) == unsig(raw)
    check("reproduction record matches the shipped reproduction rows", sha(rrep) == rp["blocks_sha256"] and rp["salt_sha256"] == run["salt_sha256"]
          and rp["identical_to_replica"] == same_bytes and rp["identical_unsigned_content"] == same_content,
          f"byte-identical {same_bytes}; content identical (signatures removed) {same_content}")
    check("G19 status reported as the preregistered criterion implies", J("gates.json")["gates"]["G19"]["status"] == ("PASS" if same_bytes else "FAIL"))
    check("gate matrix consistent with verdicts", g["gates"]["G6"]["status"] == {"REPLICATION_SUPPORTED": "PASS", "REPLICATION_INCONCLUSIVE": "PARTIAL"}.get(verdict, "FAIL")
          and g["promotion"] == ("PROMOTED" if all(x["status"] in ("PASS", "NOT_APPLICABLE") for x in g["gates"].values()) else "NOT_PROMOTED"), g["promotion"])
    check("snapshot hash signed in manifest", sha((B / "e149-snapshot.json").read_bytes()) == man["snapshot_sha256"])
    check("public snapshot equals analysis and gates (G20)", snap["promotion"] == g["promotion"] and snap["merkle_root"] == merkle and
          snap["track_a"]["mean_diff"] == round(ar["mean"], 4) and snap["status"] == {"AGI": "NOT ESTABLISHED", "RSI": "EXPERIMENTAL"})
    n_ok = sum(c[1] for c in CHECKS)
    print(f"\n{n_ok}/{len(CHECKS)} checks passed")
    return 0 if n_ok == len(CHECKS) else 1


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