#!/usr/bin/env python3
"""Add any new image in site/photos to site/data/photos.json.

Existing entries (titles, captions) are kept. New files get a title taken
from the file name and their pixel size, so the page doesn't jump around
while images load. Edit the JSON afterwards to write real titles/captions.

Usage:  python3 tools/make_photos_json.py
Needs:  pip install pillow
"""
import json
from pathlib import Path

from PIL import Image

ROOT = Path(__file__).resolve().parent.parent / "site"
PHOTOS = ROOT / "photos"
DATA = ROOT / "data" / "photos.json"
EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".avif"}

entries = json.loads(DATA.read_text()) if DATA.exists() else []
known = {entry["file"] for entry in entries}

added = 0
for path in sorted(PHOTOS.iterdir()):
    if path.suffix.lower() not in EXTENSIONS or path.name in known:
        continue
    with Image.open(path) as img:
        width, height = img.size
    title = path.stem.replace("-", " ").replace("_", " ").strip().capitalize()
    entries.append({"file": path.name, "title": title, "caption": "", "alt": "", "w": width, "h": height})
    added += 1

# Drop entries whose file was deleted.
entries = [entry for entry in entries if (PHOTOS / entry["file"]).exists()]

DATA.write_text(json.dumps(entries, indent=2, ensure_ascii=False) + "\n")
print(f"{added} new photo(s) added, {len(entries)} total.")
