#!/usr/bin/env python3
"""Bikin contact sheet kandidat foto Pexels untuk artikel listikel ke-5 (kontrak bisnis).
Jalur cadangan karena semua kunci Pexels API balas 401: unduh thumbnail dari CDN images.pexels.com.
"""
import os, sys, urllib.request
from PIL import Image, ImageDraw, ImageFont

OUT = "/home/mantapman/.hermes/profiles/atun/workspace/tslaw_listikel/kandidat5"
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"}

ID = sys.argv[1:] or ["261621", "7841818", "34862508", "8837510", "6538440", "5833330",
                      "37860169", "8654753", "3927131", "7651557", "5833238", "32975295"]
TW, TH = 320, 200
COLS = 4
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 18)
sheet = Image.new("RGB", (COLS * TW, ((len(ID) + COLS - 1) // COLS) * (TH + 26)), "white")
d = ImageDraw.Draw(sheet)

ok = []
for n, pid in enumerate(ID):
    url = (f"https://images.pexels.com/photos/{pid}/pexels-photo-{pid}.jpeg"
           f"?auto=compress&cs=tinysrgb&w=800")
    f = f"{OUT}/{pid}.jpg"
    try:
        if not os.path.exists(f):
            open(f, "wb").write(urllib.request.urlopen(
                urllib.request.Request(url, headers=UA), timeout=90).read())
        im = Image.open(f).convert("RGB")
        w, h = im.size
        r = TW / TH
        im = im.crop((0, max(0, (h - int(w / r)) // 2), w, max(0, (h - int(w / r)) // 2) + int(w / r))) \
            if w / h < r else im.crop(((w - int(h * r)) // 2, 0, (w - int(h * r)) // 2 + int(h * r), h))
        im = im.resize((TW, TH), Image.LANCZOS)
        x, y = (n % COLS) * TW, (n // COLS) * (TH + 26)
        sheet.paste(im, (x, y))
        d.text((x + 6, y + TH + 3), f"{pid}  ({Image.open(f).size[0]}x{Image.open(f).size[1]})", font=font, fill="black")
        ok.append(pid)
    except Exception as e:
        print(f"gagal {pid}: {str(e)[:60]}")

sheet.save(f"{OUT}/_contact.jpg", quality=85)
print("unduh ok:", len(ok), ok)
print("contact sheet:", f"{OUT}/_contact.jpg", sheet.size)
