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

    python3 e20_bundle_verify.py <bundle_dir>

Checks:
  * every file listed in manifest.json has the recorded SHA-256;
  * E20_FLEET_EVIDENCE.json recomputes to its content_hash;
  * the Ed25519 signature over that hash verifies.

Exit code 0 = verified, 1 = failure. This verifies integrity and provenance of a bundle; it does
NOT assert that the observed facts are true.
"""
from __future__ import annotations

import base64
import hashlib
import json
import os
import sys

try:
    from cryptography.exceptions import InvalidSignature
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
except Exception:  # pragma: no cover
    Ed25519PublicKey = None


def _canon(data) -> bytes:
    return json.dumps(data, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")


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 main(argv: list) -> int:
    if len(argv) < 2:
        print("usage: e20_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}")

    fleet_path = os.path.join(root, "E20_FLEET_EVIDENCE.json")
    if os.path.exists(fleet_path):
        bundle = json.load(open(fleet_path, encoding="utf-8"))
        claimed = bundle.get("content_hash")
        body = {k: v for k, v in bundle.items() if k not in ("content_hash", "signature")}
        if hashlib.sha256(_canon(body)).hexdigest() != claimed:
            failures.append("fleet evidence content_hash mismatch")
        sig = bundle.get("signature")
        if sig:
            if Ed25519PublicKey is None:
                failures.append("cryptography unavailable; cannot verify signature")
            else:
                try:
                    pub = Ed25519PublicKey.from_public_bytes(base64.b64decode(sig["public_key_b64"]))
                    pub.verify(base64.b64decode(sig["signature_b64"]), _canon(sig["signed_hash"]))
                except (InvalidSignature, ValueError, KeyError) as exc:
                    failures.append(f"signature invalid: {exc!r}")

    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))
