#!/usr/bin/env python3
"""Standalone offline verifier for the E91 bundle. Imports no CAIN code (stdlib + cryptography).

Checks the Ed25519 signature over MANIFEST.json, every file digest, and the arithmetic inside the
result files it knows: mission reports (verified == effects, no duplicates, event chain, 0 effects after
the kill fence) and the security lab (counts match the per-scenario rows, controls commit).
A pass proves integrity relative to the manifest and internal consistency. It does not prove that the
experiments were honestly run, and the signer is self-generated, not an independent witness.

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

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


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

    def ok(name, cond):
        nonlocal checks
        checks += 1
        if not cond:
            failed.append(name)
    raw = (root / "MANIFEST.json").read_bytes()
    man = json.loads(raw)
    try:
        from cryptography.hazmat.primitives.serialization import load_pem_public_key
        load_pem_public_key((root / "public_key.txt").read_bytes()).verify(
            base64.b64decode((root / "MANIFEST.sig").read_text().strip()), raw)
        ok("signature", True)
    except Exception:  # noqa: BLE001
        ok("signature", False)
    for rel, d in man["files"].items():
        p = root / rel
        ok(f"digest:{rel}", p.exists() and hashlib.sha256(p.read_bytes()).hexdigest() == d)
    for rel in man["files"]:
        p = root / rel
        if rel.endswith("mission_report.json") and p.exists():
            e = json.loads(p.read_text())
            v, k = e["verify"], e["kill_switch"]
            ok(f"{rel}:verified==effects", v["verified"] == v["effects"])
            ok(f"{rel}:no_duplicates", v["duplicates"] == 0)
            ok(f"{rel}:event_chain", v["event_chain_ok"] is True)
            ok(f"{rel}:no_effect_after_fence", k["effects_after_fence"] == 0)
        if rel.endswith("security/lab.json") and p.exists():
            s = json.loads(p.read_text())
            rows = [r for r in s["e91_scenarios"] if r["threat"] != "control"]
            ok(f"{rel}:attack_count", s["e91_attacks"] == len(rows))
            ok(f"{rel}:blocked_count", s["e91_blocked"] == sum(r["blocked"] for r in rows))
            ok(f"{rel}:controls_commit", s["e91_control_committed"] is True)
    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)
            target = next((c / r for r in json.loads((c / "MANIFEST.json").read_text())["files"]
                           if r.endswith(".json")), None)
            if target:
                target.write_text(target.read_text().replace("0", "1", 1))
            res["tamper_test"] = {"tampered": str(target.relative_to(c)) if target else None,
                                  "detected": not verify(c)["ok"]}
    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())
