"""Letölti minden referencia kiemelt képét, és 3 reszponzív WEBP méretet
generál belőle (400/800/1600px széles, arányos magassággal, quality=82)."""
import json
import urllib.request
from io import BytesIO
from pathlib import Path

from PIL import Image

ROOT = Path(__file__).parent.parent
DATA_PATH = ROOT / "assets" / "data" / "references.json"
OUT_DIR = ROOT / "assets" / "img" / "referenciak"
WIDTHS = [400, 800, 1600]


def download(url):
    req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
    with urllib.request.urlopen(req, timeout=30) as resp:
        return resp.read()


def main():
    refs = json.loads(DATA_PATH.read_text(encoding="utf-8"))
    OUT_DIR.mkdir(parents=True, exist_ok=True)
    for r in refs:
        if not r["image_url"]:
            print(f"SKIP (no image): {r['slug']}")
            continue
        try:
            raw = download(r["image_url"])
        except Exception as e:
            print(f"FAIL download {r['slug']}: {e}")
            continue
        im = Image.open(BytesIO(raw)).convert("RGB")
        for w in WIDTHS:
            target_path = OUT_DIR / f"{r['slug']}-{w}.webp"
            ratio = w / im.width
            h = max(1, int(im.height * ratio))
            resized = im.resize((w, h), Image.LANCZOS)
            resized.save(target_path, "WEBP", quality=82, method=6)
        print(f"OK {r['slug']}: {im.width}x{im.height} -> {WIDTHS}")


if __name__ == "__main__":
    main()
