#!/usr/bin/env python3
"""Standalone offline verifier for the E89 evidence bundle. Imports no CAIN code.

Checks: (1) the Ed25519 signature over MANIFEST.json with the bundle's public_key.txt;
(2) every file digest in the manifest; (3) the CL-Bench headline numbers, recomputed from the
per-scan reward rows in clbench/rewards.json; (4) the E88 reproduction counts; (5) the endurance
report's own arithmetic (verified == effects, no duplicates, effects after the kill fence).

A passing check proves the files are the ones the signer published and that the numbers follow from
the rows. It does not prove the signer is independent, and it does not prove the benchmark ran as
described; for that, re-run the public harness (REPRODUCTION.md).

    python3 -I verify_e89_offline.py <bundle-dir> [--tamper-test]
"""
from __future__ import annotations

import argparse
import base64
import hashlib
import json
import math
import shutil
import sys
import tempfile
from pathlib import Path


def sha(p: Path) -> str:
    return hashlib.sha256(p.read_bytes()).hexdigest()


def verify(root: Path) -> dict:
    checks, failed = 0, []

    def ok(name: str, cond: bool) -> None:
        nonlocal checks
        checks += 1
        if not cond:
            failed.append(name)

    man_raw = (root / "MANIFEST.json").read_bytes()
    man = json.loads(man_raw)
    try:
        from cryptography.hazmat.primitives.serialization import load_pem_public_key
        pub = load_pem_public_key((root / "public_key.txt").read_bytes())
        sig = base64.b64decode((root / "MANIFEST.sig").read_text().strip())
        pub.verify(sig, man_raw)
        ok("manifest_signature", True)
    except Exception:  # noqa: BLE001
        ok("manifest_signature", False)
    for rel, digest in man["files"].items():
        p = root / rel
        ok(f"digest:{rel}", p.exists() and sha(p) == digest)

    rw = json.loads((root / "clbench/rewards.json").read_text())
    head = json.loads((root / "clbench/headline.json").read_text())
    for arm, d in rw["arms"].items():
        base = {int(k): v for k, v in d["baseline"].items()}
        runs = [{int(k): v for k, v in r.items()} for r in d["runs"]]
        idx = sorted(base)
        if not runs:
            continue
        gains = [sum(r[i] - base[i] for i in idx) for r in runs]
        mean_reward = sum(sum(r.values()) for r in runs) / len(runs) / len(idx)
        h = head["arms"][arm]
        ok(f"{arm}:runs", h["runs"] == len(runs))
        ok(f"{arm}:baseline_mean", math.isclose(h["baseline_mean"], sum(base.values()) / len(idx), abs_tol=1e-4))
        ok(f"{arm}:mean_reward", math.isclose(h["mean_reward_per_scan"], mean_reward, abs_tol=1e-4))
        ok(f"{arm}:gain_per_scan", math.isclose(h["gain_per_scan"], sum(gains) / len(gains) / len(idx), abs_tol=1e-4))
        pm = {i: sum(r[i] for r in runs) / len(runs) for i in idx}
        ok(f"{arm}:scans_better", h["scans_better_than_baseline"] == sum(pm[i] > base[i] for i in idx))

    rep = json.loads((root / "e88/E89_E88_REPRODUCTION_MATRIX.json").read_text())
    ok("e88:reproduced_count", sum(c["verdict"] == "REPRODUCED" for c in rep["checks"]) == rep["counts"].get("REPRODUCED"))

    end = root / "endurance/mission_report.json"
    if end.exists():
        e = json.loads(end.read_text())
        v = e["verify"]
        ok("endurance:verified_eq_effects", v["verified"] == v["effects"])
        ok("endurance:no_duplicates", v["duplicates"] == 0)
        ok("endurance:chain", v["event_chain_ok"] is True)
        ok("endurance:no_effect_after_fence", e["kill_switch"]["effects_after_fence"] == 0)
    return {"checks": checks, "passed": checks - len(failed), "failed": failed, "ok": not failed}


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("bundle")
    ap.add_argument("--tamper-test", action="store_true")
    a = ap.parse_args()
    root = Path(a.bundle)
    res = verify(root)
    if a.tamper_test:
        with tempfile.TemporaryDirectory() as t:
            c = Path(t) / "b"
            shutil.copytree(root, c)
            h = c / "clbench/headline.json"
            d = json.loads(h.read_text())
            first = next(iter(d["arms"]))
            d["arms"][first]["mean_reward_per_scan"] += 0.05
            h.write_text(json.dumps(d))
            t_res = verify(c)
        res["tamper_test"] = {"tampered": "clbench/headline.json", "detected": not t_res["ok"],
                              "failed_checks": len(t_res["failed"])}
    print(json.dumps(res, indent=1))
    return 0 if res["ok"] and (not a.tamper_test or res["tamper_test"]["detected"]) else 1


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