#!/usr/bin/env python3
"""Standalone E92 offline verifier (stdlib + cryptography, no CAIN imports)."""
from __future__ import annotations

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


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


def check(root: Path):
    checks = []
    def ok(c, n, d=""):
        checks.append((bool(c), f"{n}{(': ' + d) if d and not c else ''}"))
    man = json.loads((root / "MANIFEST.json").read_text())
    body = {k: v for k, v in man.items() if k != "signature"}
    ok(man.get("schema") == "cain.e92.evidence.bundle.v1", "schema")
    ok(man.get("status") == "RELEASED — PARTIAL EVIDENCE", "status")
    ok(man.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())
        pub.verify(base64.b64decode(man["signature"]), canonical(body))
        ok(True, "signature")
    except Exception as exc:  # noqa: BLE001
        ok(False, "signature", str(exc))
    for rel, h in man["files"].items():
        p = root / rel
        ok(p.exists() and hashlib.sha256(p.read_bytes()).hexdigest() == h, f"digest {rel}")
    ok(not (root / "PRIVATE_KEY.pem").exists(), "no private key")
    rows = [json.loads(x) for x in (root / "artifacts/e92/run/rows.jsonl").read_text().splitlines() if x]
    for arm in ("D", "G", "F", "G2"):
        xs = [r for r in rows if r["arm"] == arm]
        k = sum(1 for r in xs if r["accepted"])
        ok(k == man["claims"]["run"][arm]["accepted"], f"{arm} accepted")
        ok(len(xs) == man["claims"]["run"][arm]["n"], f"{arm} n")
    c = man["claims"]["candidates"]
    ok(c[0] >= c[1] + c[3], "candidate accounting")
    ok(c[3] == 3, "three procedures promoted")
    ok(man["claims"]["e91_baseline"] == "REPRODUCED", "E91 baseline reproduced")
    sec = json.loads((root / "artifacts/e92/security/lab.json").read_text())
    ok(sec["all_blocked"] and sec["bypassed"] == 0, "security lab blocked")
    rep = json.loads((root / "artifacts/e92/replication/results.json").read_text())
    ok(rep["arms"]["G2"]["accepted"] == 120, "replication G2")
    report = (root / "docs/evolution-92/E92_EXECUTIVE_REPORT.md").read_text().lower()
    ok("partial evidence" in report, "report says PARTIAL")
    for phrase in ("achieved agi", "achieved vagi", "achieved superintelligence", "production-ready",
                   "independently certified"):
        ok(phrase not in report, f"no overclaim: {phrase}")
    return checks


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("bundle")
    ap.add_argument("--tamper-test", action="store_true")
    a = ap.parse_args()
    root = Path(a.bundle)
    checks = check(root)
    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")
    if a.tamper_test and not failed:
        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))
            bad = [x for x in check(c) if not x[0]]
            print(f"tamper test: {len(bad)} failures (expected > 0)")
            if not bad:
                return 1
    return 1 if failed else 0


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