"""Verify this local demonstration bundle against a separately trusted digest.

This checks bytes, not source authenticity, capture time, or legal admissibility.
Run on a stable local copy; this is not a sandbox for hostile concurrent writers.
"""

import hashlib
import json
from pathlib import Path
import re
import sys


def verify(root, expected_manifest_sha256):
    if not re.fullmatch(r"[0-9a-f]{64}", expected_manifest_sha256):
        raise ValueError("expected manifest digest must be lowercase SHA-256")
    manifest_path = root / "manifest.json"
    if manifest_path.is_symlink():
        raise ValueError("manifest must be a regular local file")
    manifest_bytes = manifest_path.read_bytes()
    # Authenticate the reference before trusting its artifact paths or hashes.
    if hashlib.sha256(manifest_bytes).hexdigest() != expected_manifest_sha256:
        raise ValueError("manifest digest mismatch")
    manifest = json.loads(manifest_bytes)
    if manifest.get("schema_version") != 1 or not manifest.get("artifacts"):
        raise ValueError("unsupported schema or empty artifact list")
    seen = set()
    for artifact in manifest["artifacts"]:
        name = artifact["path"]
        # The demonstration supports flat file names only, never path traversal.
        if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", name):
            raise ValueError("artifact path must be a flat file name")
        if name in seen or name in {"manifest.json", "verify.py"}:
            raise ValueError("duplicate or reserved artifact path")
        seen.add(name)
        path = root / name
        if path.is_symlink() or not path.is_file():
            raise ValueError(f"missing or non-regular artifact: {name}")
        data = path.read_bytes()
        if len(data) != artifact["bytes"]:
            raise ValueError(f"size mismatch: {name}")
        if hashlib.sha256(data).hexdigest() != artifact["sha256"]:
            raise ValueError(f"digest mismatch: {name}")
    return len(seen)


if __name__ == "__main__":
    if len(sys.argv) != 3:
        sys.exit("Usage: python3 verify.py BUNDLE_DIR EXPECTED_MANIFEST_SHA256")
    try:
        count = verify(Path(sys.argv[1]), sys.argv[2])
    except (OSError, ValueError, KeyError, TypeError) as error:
        sys.exit(f"FAIL: {error}")
    print(f"PASS: {count} artifact(s) match the trusted manifest; provenance unverified.")
