#!/usr/bin/env python3
"""Verify IMAGES_REGISTRY.md entries exist on disk and match .typ references."""
from __future__ import annotations

import re
import sys
from pathlib import Path


def main() -> int:
    report = Path(__file__).resolve().parent.parent
    repo = report.parent
    images = report / "images"
    registry = images / "IMAGES_REGISTRY.md"
    typ = report / "Пояснительная_записка_ПытковРЕ.typ"
    errors = 0

    if not registry.exists():
        print("Missing IMAGES_REGISTRY.md", file=sys.stderr)
        return 1

    rows = re.findall(
        r"\|\s*\d+\s*\|\s*([^\|]+?)\s*\|\s*(\w+)\s*\|",
        registry.read_text(encoding="utf-8"),
    )
    rows = [(f.strip(), s.strip()) for f, s in rows if f.startswith("fig_")]
    for fname, status in rows:
        p = images / fname
        if not p.exists():
            print(f"MISSING file: {fname} (status {status})", file=sys.stderr)
            errors += 1
        elif status == "ready" and p.stat().st_size < 1000:
            print(f"WARN small file: {fname}", file=sys.stderr)

    if typ.exists():
        text = typ.read_text(encoding="utf-8")
        for m in re.finditer(r'image\("(?:Report/)?images/([^"]+)"', text):
            f = images / m.group(1)
            if not f.exists():
                print(f"MISSING in typ: images/{m.group(1)}", file=sys.stderr)
                errors += 1

    if errors:
        print(f"check_images: {errors} error(s)", file=sys.stderr)
        return 1
    print("check_images: OK", file=sys.stderr)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
