#!/usr/bin/env python3
"""Offline verifier for the E26 completion bundle. Zero CAIN imports."""
from __future__ import annotations

import hashlib, importlib.util, json, os, 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("e26_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: e26_completion_verify.py <bundle_dir>", file=sys.stderr); return 2
    root = os.path.abspath(argv[1]); failures = []
    manifest = json.load(open(os.path.join(root, "manifest.json"), 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}")
    # independently verify the settlement proof inside the completion bundle
    proof = os.path.join(root, "E26_SETTLEMENT_PROOF.json")
    verifier = os.path.join(root, "verifier.py")
    if os.path.exists(proof) and os.path.exists(verifier):
        for problem in _load(verifier).verify(json.load(open(proof, encoding="utf-8"))):
            failures.append("settlement proof: " + problem)
    # completion status consistency
    comp = os.path.join(root, "CAIN42_E26_COMPLETION_EVIDENCE_BUNDLE.json")
    if os.path.exists(comp):
        c = json.load(open(comp, encoding="utf-8"))
        mp = c.get("mandatory_fail", [])
        if c.get("final_status") == "COMPLETE" and mp:
            failures.append("completion claims COMPLETE with failing mandatory gates")
    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))
