#!/usr/bin/env python3
"""Contact sheet kandidat foto Pexels untuk artikel perdata TSLaw 14 Okt 2026."""
import os, urllib.request
from PIL import Image

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
OUT = f"{WS}/tslaw_listikel"
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 = ["8815837", "7876044", "8112126", "4427543", "7841463", "8729731",
       "6077447", "4922086", "8729723", "8112111", "7875868", "7876203",
       "34817075", "7841473", "6077665", "3807741"]

thumbs = []
for i in IDS:
    u = f"https://images.pexels.com/photos/{i}/pexels-photo-{i}.jpeg?auto=compress&cs=tinysrgb&w=600"
    try:
        d = urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=90).read()
        f = f"{OUT}/_thumb_{i}.jpg"
        open(f, "wb").write(d)
        thumbs.append((i, Image.open(f).convert("RGB")))
        print(f"  ok {i} {Image.open(f).size}")
    except Exception as e:
        print(f"  gagal {i}: {str(e)[:60]}")

if thumbs:
    kol, bar = 4, (len(thumbs) + 3) // 4
    tw, th, pad = 380, 253, 26
    sheet = Image.new("RGB", (kol * (tw + pad) + pad, bar * (th + 40) + pad), "white")
    from PIL import ImageDraw
    dr = ImageDraw.Draw(sheet)
    for n, (i, im) in enumerate(thumbs):
        r, c = divmod(n, kol)
        x = pad + c * (tw + pad)
        y = pad + r * (th + 40)
        sheet.paste(im.resize((tw, th), Image.LANCZOS), (x, y))
        dr.text((x + 4, y + th + 6), f"{n}: {i}", fill="black")
    f = f"{OUT}/_contact_sheet.jpg"
    sheet.save(f, quality=88)
    print("contact sheet:", f, sheet.size)
