#!/usr/bin/env python3
"""Unduh kandidat foto Pexels (CDN, tanpa API key) dan buat contact sheet untuk dipilih."""
import os, urllib.request, urllib.error
from PIL import Image, ImageDraw

OUT = "/home/mantapman/.hermes/profiles/atun/workspace/tslaw_listikel/kandidat6"
os.makedirs(OUT, exist_ok=True)
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36"}
IDS = ["261621", "7781900", "6077665", "7504780", "7876037", "6326287", "7821576", "7658310", "3747070", "6550126"]

TW, TH = 1000, 567
ok = []
for pid in IDS:
    f = f"{OUT}/{pid}.jpg"
    if not os.path.exists(f):
        u = f"https://images.pexels.com/photos/{pid}/pexels-photo-{pid}.jpeg?auto=compress&cs=tinysrgb&w=1600"
        try:
            d = urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=120).read()
            open(f, "wb").write(d)
        except Exception as e:
            print(f"  {pid}: gagal {str(e)[:60]}")
            continue
    im = Image.open(f).convert("RGB")
    w, h = im.size
    r = TW / TH
    if w / h > r:
        im = im.crop(((w - int(h * r)) // 2, 0, (w - int(h * r)) // 2 + int(h * r), h))
    else:
        im = im.crop((0, (h - int(w / r)) // 2, w, (h - int(w / r)) // 2 + int(w / r)))
    im = im.resize((TW, TH), Image.LANCZOS)
    p = f"{OUT}/crop_{pid}.jpg"
    im.save(p, "JPEG", quality=85)
    ok.append((pid, p, os.path.getsize(p)))
    print(f"  {pid}: {Image.open(f).size} -> crop ok")

# contact sheet 3 kolom
kol = 3
bar = 2
cw, ch = TW // 2, TH // 2
rows = (len(ok) + kol - 1) // kol
sheet = Image.new("RGB", (kol * (cw + bar) + bar, rows * (ch + bar + 26) + bar), (25, 25, 30))
d = ImageDraw.Draw(sheet)
for i, (pid, p, _) in enumerate(ok):
    im = Image.open(p).resize((cw, ch), Image.LANCZOS)
    x = bar + (i % kol) * (cw + bar)
    y = bar + (i // kol) * (ch + bar + 26)
    sheet.paste(im, (x, y))
    d.text((x + 6, y + ch + 6), f"{i+1}. pexels {pid}", fill=(255, 255, 255))
sp = f"{OUT}/contact_sheet.jpg"
sheet.save(sp, "JPEG", quality=88)
print(f"contact sheet: {sp} {sheet.size}")
