#!/usr/bin/env python3
"""Verify registry artifacts without mutating the working tree or comparing to HEAD."""
from __future__ import annotations

import hashlib
import os
import subprocess
import sys
import tempfile
from pathlib import Path

PR7 = Path(__file__).resolve().parents[1]
EXPECTED = PR7 / "generated"
BUILDER = PR7 / "registry" / "build_full_registry.py"


def digest(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


with tempfile.TemporaryDirectory(prefix="vaultfire-v3-registry-") as directory:
    actual = Path(directory)
    environment = {**os.environ, "SOURCE_DATE_EPOCH": "0", "VAULTFIRE_REGISTRY_OUTPUT_DIR": directory}
    completed = subprocess.run(
        [sys.executable, str(BUILDER)],
        cwd=PR7.parent,
        env=environment,
        text=True,
        capture_output=True,
        check=False,
    )
    if completed.returncode:
        sys.stderr.write(completed.stdout + completed.stderr)
        raise SystemExit(completed.returncode)
    generated = sorted(path.name for path in actual.iterdir() if path.is_file())
    missing = [name for name in generated if not (EXPECTED / name).is_file()]
    changed = [name for name in generated if not missing and digest(actual / name) != digest(EXPECTED / name)]
    if missing or changed:
        print({"missing": missing, "changed": changed}, file=sys.stderr)
        raise SystemExit(1)
    print(f"registry determinism verified in temporary output: {len(generated)} files")
