#!/usr/bin/env python3 """Materialize MedWeave images from user-provided, legally obtained roots.""" from __future__ import annotations import argparse import hashlib import json import os import shutil from pathlib import Path from typing import Any def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def load_manifest(path: Path) -> dict[str, dict[str, Any]]: required: dict[str, dict[str, Any]] = {} with path.open(encoding="utf-8") as handle: for line_number, line in enumerate(handle, 1): if not line.strip(): continue row = json.loads(line) digest = str(row["sha256"]) expected_path = str(row["expected_path"]) previous = required.get(digest) if previous and previous["expected_path"] != expected_path: raise ValueError( f"Digest {digest} has conflicting paths at line {line_number}: " f"{previous['expected_path']} vs {expected_path}" ) required[digest] = row return required def write_missing(path: Path, rows: list[dict[str, Any]]) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8", newline="\n") as handle: for row in rows: handle.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n") def main() -> None: parser = argparse.ArgumentParser( description=( "Hash user-provided files and materialize exact matches into the " "MedWeave snapshot layout. The command never downloads source data." ) ) parser.add_argument("--manifest", type=Path, required=True) parser.add_argument("--output-root", type=Path, required=True) parser.add_argument("--search-root", type=Path, action="append", required=True) parser.add_argument("--copy", action="store_true", help="Copy instead of creating symlinks") parser.add_argument( "--missing-report", type=Path, default=None, help="Default: /missing_images.jsonl", ) parser.add_argument( "--allow-missing", action="store_true", help="Return success even when some assets remain unresolved", ) args = parser.parse_args() required = load_manifest(args.manifest) already_present: set[str] = set() unresolved: dict[str, dict[str, Any]] = {} for digest, row in required.items(): target = args.output_root / row["expected_path"] if target.is_file() and sha256_file(target) == digest: already_present.add(digest) else: unresolved[digest] = row found: dict[str, Path] = {} scanned_files = 0 for root in args.search_root: if not root.is_dir(): raise NotADirectoryError(root) for path in root.rglob("*"): if not path.is_file(): continue scanned_files += 1 digest = sha256_file(path) if digest in unresolved and digest not in found: found[digest] = path.resolve() if len(found) == len(unresolved): break if len(found) == len(unresolved): break for digest, source in found.items(): target = args.output_root / unresolved[digest]["expected_path"] target.parent.mkdir(parents=True, exist_ok=True) if target.exists() or target.is_symlink(): if target.is_file() and sha256_file(target) == digest: continue raise RuntimeError(f"Refusing to overwrite non-matching file: {target}") if args.copy: shutil.copy2(source, target) else: os.symlink(source, target) missing_digests = sorted(set(unresolved) - set(found)) missing_rows = [required[digest] for digest in missing_digests] missing_report = args.missing_report or (args.output_root / "missing_images.jsonl") write_missing(missing_report, missing_rows) summary = { "assets_in_manifest": len(required), "already_present": len(already_present), "scanned_files": scanned_files, "materialized_now": len(found), "still_missing": len(missing_rows), "missing_report": str(missing_report), "mode": "copy" if args.copy else "symlink", } print(json.dumps(summary, indent=2, sort_keys=True)) if missing_rows and not args.allow_missing: raise SystemExit(2) if __name__ == "__main__": main()