#!/usr/bin/env python3
"""Standalone offline verifier for the E91 evaluation-slice bundle.

    python3 verify_e91_eval_offline.py <bundle-dir>

Imports no CAIN code. Verifies the signed manifest, every file digest/size, the raw-row arm rates,
the 120-task count and the PARTIAL status. Exit 0 = all checks pass.
"""
from __future__ import annotations

import argparse
import base64
import hashlib
import json
import sys
from pathlib import Path


def canonical(obj):
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()


def sha_file(p: Path) -> str:
    h = hashlib.sha256()
    with open(p, "rb") as fh:
        for chunk in iter(lambda: fh.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def check(root: Path):
    checks = []

    def ok(cond, name, detail=""):
        checks.append((bool(cond), f"{name}{(': ' + detail) if detail and not cond else ''}"))

    mp = root / "MANIFEST.json"
    ok(mp.exists(), "MANIFEST.json present")
    if not mp.exists():
        return checks
    m = json.loads(mp.read_text(encoding="utf-8"))
    body = {k: v for k, v in m.items() if k != "signature"}
    ok(m.get("schema") == "cain.e91.eval.public.bundle.v1", "schema")
    ok(m.get("evolution") == "E91", "evolution")
    ok(m.get("overall_status") == "PARTIAL", "status is PARTIAL")
    ok(m.get("independent_witness") is False, "no independent witness claimed")
    try:
        from cryptography.hazmat.primitives import serialization
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        pub = serialization.load_pem_public_key((root / "PUBLIC_KEY.txt").read_bytes())
        assert isinstance(pub, Ed25519PublicKey)
        pub.verify(base64.b64decode(m["signature"]), canonical(body))
        ok(True, "manifest signature")
    except Exception as exc:  # noqa: BLE001
        ok(False, "manifest signature", f"{type(exc).__name__}: {exc}")
    listed = {f["path"]: f for f in m.get("files", [])}
    for rel, meta in listed.items():
        p = root / rel
        ok(p.exists(), f"file {rel}")
        if p.exists():
            ok(sha_file(p) == meta["sha256"], f"digest {rel}")
            ok(p.stat().st_size == meta["size"], f"size {rel}")
    ok(not (root / "PRIVATE_KEY.pem").exists(), "no private key")
    extra = [str(p.relative_to(root)).replace("\\", "/") for p in root.rglob("*")
             if p.is_file() and str(p.relative_to(root)).replace("\\", "/") not in listed
             and p.name not in ("MANIFEST.json", "PUBLIC_KEY.txt", "RELEASE_STATUS.json", "index.html")]
    ok(not extra, "no unlisted files", str(extra[:5]))
    rows = [json.loads(x) for x in (root / "artifacts/e91/eval/rows.jsonl").read_text().splitlines() if x]
    ok(len([r for r in rows if r["split"] == "heldout"]) == 1320, "1,320 held-out decisions")
    for arm, claim in m["claims"]["arms"].items():
        xs = [r for r in rows if r["split"] == "heldout" and r["arm"] == arm]
        k = sum(1 for r in xs if r["accepted"])
        ok(len(xs) == claim["n"], f"{arm}: n")
        ok(k == claim["accepted"], f"{arm}: accepted")
        ok(abs(k / len(xs) - claim["rate"]) < 1e-6, f"{arm}: rate")
    ok(m["manifest_task_count"] == 120, "120 held-out tasks")
    ok(m["claims"]["overall_status"] == "PARTIAL", "claims status PARTIAL")
    report = (root / "docs/evolution-91-eval/E91_EVAL_REPORT.md").read_text(encoding="utf-8").lower()
    ok("status: partial" in report, "report says PARTIAL")
    for phrase in ("has achieved agi", "has achieved superintelligence", "is production-ready",
                   "is independently certified", "operates thousands of production agents"):
        ok(phrase not in report, f"no affirmative overclaim: {phrase}")
    return checks


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("bundle")
    args = ap.parse_args()
    checks = check(Path(args.bundle))
    failed = [c for c in checks if not c[0]]
    for good, name in checks:
        print(("PASS " if good else "FAIL ") + name)
    print(f"\n{len(checks) - len(failed)}/{len(checks)} checks passed")
    return 1 if failed else 0


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