#!/usr/bin/env python3
"""Verify Report/images files exist; fail on missing diagram PNGs."""
from __future__ import annotations

import re
import sys
from pathlib import Path

REQUIRED_READY = (
    {f"fig_{i:02d}_" for i in range(1, 5)}
    | {f"fig_11_"}
    | {f"fig_{i:02d}_" for i in range(14, 24)}
    | {f"fig_32_"}
)

WARN_PLACEHOLDER: set[str] = set()


def main() -> int:
    report = Path(__file__).resolve().parents[1]
    images = report / "images"
    registry = images / "IMAGES_REGISTRY.md"
    text = registry.read_text(encoding="utf-8")
    errors: list[str] = []
    warns: list[str] = []

    for line in text.splitlines():
        if "|" not in line or "fig_" not in line:
            continue
        cols = [c.strip() for c in line.split("|")]
        if len(cols) < 4:
            continue
        fname, status = cols[2], cols[3]
        if not fname.startswith("fig_"):
            continue
        path = images / fname
        if not path.is_file():
            errors.append(f"missing file: {fname}")
            continue
        if status == "placeholder":
            for prefix in WARN_PLACEHOLDER:
                if fname.startswith(prefix):
                    warns.append(f"placeholder: {fname}")
                    break
        elif status == "ready":
            for prefix in REQUIRED_READY:
                if fname.startswith(prefix):
                    if path.stat().st_size < 500:
                        errors.append(f"too small (placeholder?): {fname}")
                    break

    for w in warns:
        print(f"WARN {w}", file=sys.stderr)
    for e in errors:
        print(f"ERROR {e}", file=sys.stderr)

    if errors:
        return 1
    print(f"OK: images check passed ({len(list(images.glob('fig_*')))} files)")
    return 0


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