#!/usr/bin/env python3
"""Railed offline SHA-256 integrity verifier. Standard library only; never runs model code."""
import argparse
import hashlib
import json
from pathlib import Path
import re
import sys


def main():
    parser = argparse.ArgumentParser(description="Verify a local artifact against its Railed manifest")
    parser.add_argument("--manifest", required=True, type=Path, help="Downloaded JSON rail manifest")
    parser.add_argument("--file", required=True, type=Path, help="Downloaded model artifact")
    args = parser.parse_args()
    try:
        manifest = json.loads(args.manifest.read_text(encoding="utf-8"))
        if not isinstance(manifest, dict):
            raise ValueError("Manifest must be an object")
        # Current Railed v0.6+ manifests embed artifact sha256 in model metadata.
        model = manifest.get("model", {})
        if not isinstance(model, dict):
            raise ValueError("Missing model metadata")
        expected = None
        for candidate in (model.get("sha256"), model.get("artifact_sha256"),
                          manifest.get("artifact_sha256"), model.get("checksum_sha256")):
            if isinstance(candidate, str) and re.fullmatch(r"[a-fA-F0-9]{64}", candidate):
                expected = candidate.lower()
                break
        if expected is None:
            # Accommodate a nested artifacts structure only when explicitly present.
            artifacts = manifest.get("artifacts")
            if isinstance(artifacts, dict):
                candidate = artifacts.get("sha256")
                if isinstance(candidate, str) and re.fullmatch(r"[a-fA-F0-9]{64}", candidate):
                    expected = candidate.lower()
        if expected is None:
            print("ERROR: No valid publisher-supplied SHA-256 in manifest", file=sys.stderr)
            return 2
        digest = hashlib.sha256()
        with args.file.open("rb") as stream:
            for block in iter(lambda: stream.read(1024 * 1024), b""):
                digest.update(block)
        actual = digest.hexdigest()
        print("Expected:", expected)
        print("Actual:  ", actual)
        if actual != expected:
            print("FAIL: Artifact hash mismatch. Do not load the file.")
            return 1
        print("PASS: File matches the checksum declared in the manifest.")
        print("NOTE: This does not prove publisher authenticity, model safety or enforced rails.")
        return 0
    except (OSError, ValueError, json.JSONDecodeError) as exc:
        print("ERROR:", exc, file=sys.stderr)
        return 2


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