#!/usr/bin/env python3
"""Verify this evidence bundle against MANIFEST.json. Standard library only.

    python3 verify_bundle.py

Exit 0 when every listed file exists and its SHA-256/size match; 1 otherwise.
This checks the bundle's integrity. It does not re-run the PBFT or soak verifiers.
"""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent


def main() -> int:
    try:
        manifest = json.loads((ROOT / "MANIFEST.json").read_text())
    except (OSError, ValueError) as exc:
        print(f"cannot read MANIFEST.json: {exc}", file=sys.stderr)
        return 1
    files = manifest.get("files") or {}
    if not files:
        print("MANIFEST.json lists no files", file=sys.stderr)
        return 1
    bad, ok = [], 0
    for rel, meta in sorted(files.items()):
        p = ROOT / rel
        if not p.is_file():
            bad.append(f"{rel}: missing")
            continue
        data = p.read_bytes()
        digest = hashlib.sha256(data).hexdigest()
        if digest != meta.get("sha256") or len(data) != meta.get("size"):
            bad.append(f"{rel}: hash/size mismatch")
            continue
        ok += 1
    if bad:
        for line in bad:
            print("FAIL " + line)
        print(f"FAILED: {len(bad)} of {len(files)} file(s)")
        return 1
    print(f"OK: {ok} files match MANIFEST.json")
    print(f"bundle: {manifest.get('bundle')}  evidence_class: {manifest.get('evidence_class')}")
    print(f"soak: {manifest.get('soak_status')}")
    return 0


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