from __future__ import annotations

import argparse
import json
import re
from pathlib import Path


IMAGE_RE = re.compile(r"!\[[^\]]*\]\(([^)]+)\)")


def validate_file(path: Path) -> dict:
    text = path.read_text(encoding="utf-8", errors="replace")
    refs = IMAGE_RE.findall(text)
    missing = []
    for ref in refs:
        if ref.startswith(("http://", "https://", "data:")):
            continue
        if not (path.parent / ref).exists() and not Path(ref).exists():
            missing.append(ref)
    return {
        "file": str(path),
        "image_refs": len(refs),
        "missing_refs": len(missing),
        "missing_samples": missing[:50],
    }


def collect_markdown(path: Path) -> list[Path]:
    if path.is_file():
        return [path]
    return sorted(path.rglob("*.md"))


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("target", type=Path)
    args = parser.parse_args()

    results = [validate_file(path) for path in collect_markdown(args.target)]
    print(json.dumps({"files": len(results), "results": results}, indent=2))
    raise SystemExit(1 if any(result["missing_refs"] for result in results) else 0)


if __name__ == "__main__":
    main()
