#!/usr/bin/env python3
"""Standalone offline verifier for the CAIN-42 E154 Phase 1 evidence bundle (stdlib only; imports no CAIN code).
    python3 -I verify_e154_offline.py <bundle_dir>
Checks the signed manifest and Merkle root, recomputes API usage totals from the request ledger, confirms every indexed
work passed source verification, recomputes the evidence-audit counts, and checks the snapshot against the files.
Passing means the bundle is internally consistent; it does not prove any scientific claim.
"""
import hashlib, json, re, 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



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 mcnemar(b, c):
    n = b + c
    return sum(math.comb(n, k) for k in range(b, n + 1)) / 2 ** n if n else 1.0


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)))
    print(("PASS " if ok else "FAIL ") + name + (f"  [{detail}]" if detail else ""))
    return bool(ok)


def merkle(files):
    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)]
    return leaves[0].hex()


CHECKS = []


def main():
    B = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    J = lambda p: json.loads((B / p).read_text())
    man = J("MANIFEST.json")
    ok = all((B / f).exists() and sha((B / f).read_bytes()) == h for f, h in man["files"].items())
    check("every manifest file present with matching SHA-256", ok, f"{len(man['files'])} files")
    check("Merkle root recomputes", merkle(man["files"]) == man["merkle_root"] == (B / "MERKLE_ROOT.txt").read_text().strip(), man["merkle_root"][:16])
    check("manifest Ed25519 signature valid", ed25519_verify(man["bundle_pubkey_ed25519"], canon({k: v for k, v in man.items() if k != "signature"}).encode(), man["signature"]))
    L = [json.loads(l) for l in (B / "E154_API_REQUEST_LEDGER.jsonl").read_text().splitlines() if l.strip()]
    S = [x for x in L if x["event"] == "settle"]; U = J("E154_ANTHROPIC_USAGE.json")
    check("request count recomputes from the ledger", len(S) == U["requests"], str(len(S)))
    check("spend recomputes from the ledger", abs(sum(x["usd"] for x in S) - U["usd_estimate"]) < 1e-6, f"${U['usd_estimate']:.4f}")
    toks = {k: sum((x.get("usage") or {}).get(k, 0) for x in S) for k in ("input", "output", "cache_read", "cache_write", "web_search_requests")}
    check("token totals recompute from the ledger", toks == U["tokens"], json.dumps(toks))
    check("spend within the hard ceiling", U["usd_estimate"] <= U["budget_usd"], f"${U['usd_estimate']:.4f} <= ${U['budget_usd']}")
    check("every reservation settled", {x["id"] for x in L if x["event"] == "reserve"} == {x["id"] for x in S})
    check("every settled request has a request id or a failure status", all(x.get("request_id") or x["status"] != "OK" for x in S))
    check("no credential material in the ledger", not re.search(r"sk-ant-[A-Za-z0-9_-]{10,}", (B / "E154_API_REQUEST_LEDGER.jsonl").read_text()))
    sv = J("literature/SOURCE_VERIFICATION.json"); li = J("literature/LITERATURE_INDEX.json")
    ver = {(r["title"], r["url"]): r["status"] for r in sv["rows"]}
    check("every indexed work passed source verification", all(ver.get((w["title"], w["url"])) in ("VERIFIED_SOURCE", "REACHABLE_TITLE_UNCONFIRMED") for w in li["works"]), f"{li['n']} works")
    check("every indexed URL was returned by the API's own web search", all(r["in_search_results"] for r in sv["rows"] if (r["title"], r["url"]) in {(w["title"], w["url"]) for w in li["works"]}))
    ea = J("E154_EVIDENCE_AUDIT.json")
    check("evidence-audit counts recompute", ea["checked"] == len(ea["rows"]) and len(ea["unsupported"]) == sum(not r["found_in_evidence"] for r in ea["rows"]), f"{len(ea['unsupported'])}/{ea['checked']} unsupported")
    d = J("E154_RESEARCH_DIRECTIONS.json")["json"]["directions"]; rv = J("E154_REVIEW.json")["json"]["reviews"]
    check("every direction was adversarially reviewed", {x["id"] for x in d} <= {x["id"] for x in rv}, f"{len(d)} directions")
    fc = J("E154_FORECASTS.json")
    check("forecasts hash matches (sealed before outcomes)", hashlib.sha256(json.dumps(fc["forecasts"], sort_keys=True).encode()).hexdigest() == fc["forecasts_sha256"], f"{len(fc['forecasts'])} forecasts")
    check("forecast probabilities in [0,1]", all(0 <= f["probability"] <= 1 for f in fc["forecasts"]))
    hy = J("E154_HYPOTHESES.json")
    check("every research role returned hypotheses", all(v.get("status") == "OK" and (v.get("json") or {}).get("hypotheses") for v in hy.values()), ", ".join(hy))
    snap = J("e154-snapshot.json")
    check("snapshot matches usage, literature, review and audit", snap["api"]["requests"] == U["requests"] and abs(snap["api"]["usd"] - U["usd_estimate"]) < 1e-6 and snap["literature"]["verified"] == li["n"]
          and snap["review"]["verdicts"] == {v: sum(1 for x in rv if x["verdict"] == v) for v in ("PROCEED", "REVISE", "REJECT")} and snap["evidence_audit"]["unsupported"] == len(ea["unsupported"]))
    check("status line present", snap["status"] == {"AGI": "NOT ESTABLISHED", "RSI": "EXPERIMENTAL"})
    n = sum(ok for _, ok in CHECKS); print(f"{n}/{len(CHECKS)} checks passed"); sys.exit(0 if n == len(CHECKS) else 1)


if __name__ == "__main__":
    main()
