#!/usr/bin/env python3
"""Offline verifier for an E22 evidence bundle. Zero CAIN imports.

    python3 e22_bundle_verify.py <bundle_dir>

Checks manifest.json hashes, then independently verifies E22_EXECUTION_PROOF.json via the bundled
clean-room verifier (verifier.py).
"""
from __future__ import annotations

import hashlib
import importlib.util
import json
import os
import sys


def _sha_file(path: str) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as fh:
        for chunk in iter(lambda: fh.read(65536), b""):
            h.update(chunk)
    return h.hexdigest()


def _load(path: str):
    spec = importlib.util.spec_from_file_location("e22_verifier", path)
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod


def main(argv: list) -> int:
    if len(argv) < 2:
        print("usage: e22_bundle_verify.py <bundle_dir>", file=sys.stderr)
        return 2
    root = os.path.abspath(argv[1])
    failures = []
    manifest_path = os.path.join(root, "manifest.json")
    if not os.path.exists(manifest_path):
        print("FAIL: manifest.json missing"); return 1
    manifest = json.load(open(manifest_path, encoding="utf-8"))
    for rel, expected in manifest.get("files", {}).items():
        p = os.path.join(root, rel)
        if not os.path.exists(p):
            failures.append(f"missing: {rel}")
        elif _sha_file(p) != expected:
            failures.append(f"hash mismatch: {rel}")

    proof_path = os.path.join(root, "E22_EXECUTION_PROOF.json")
    verifier_path = os.path.join(root, "verifier.py")
    if os.path.exists(proof_path) and os.path.exists(verifier_path):
        mod = _load(verifier_path)
        proof = json.load(open(proof_path, encoding="utf-8"))
        for problem in mod.verify(proof):
            failures.append("execution proof: " + problem)

    if failures:
        print("BUNDLE FAILED:")
        for f in failures:
            print("  -", f)
        return 1
    print(f"BUNDLE VERIFIED: {root}")
    print(f"  files: {len(manifest.get('files', {}))}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main(sys.argv))
