#!/usr/bin/env python3
"""Contact sheet berlabel untuk artikel 13: kandidat foto dari query ibu/anak + dokumen kantor hukum."""
import os, urllib.request
from PIL import Image, ImageDraw, ImageFont

OUT = "/home/mantapman/.hermes/profiles/atun/workspace/tslaw_listikel"
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36"}
IDS = ["9240632", "8698024", "7946700", "7358374", "11163636", "21073553",
       "7951671", "7876197", "7951886", "4792286", "34410146", "6077328"]
F = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 40)

cw, ch, cols = 640, 364, 3
rows = (len(IDS) + cols - 1) // cols
sheet = Image.new("RGB", (cols * cw, rows * ch), "white")
d = ImageDraw.Draw(sheet)
for n, pid in enumerate(IDS):
    u = f"https://images.pexels.com/photos/{pid}/pexels-photo-{pid}.jpeg?auto=compress&cs=tinysrgb&w=900"
    try:
        data = urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=120).read()
    except Exception as e:
        print(f"lewat {pid}: {str(e)[:60]}")
        continue
    p = f"{OUT}/_kandidat13b_{pid}.jpg"
    open(p, "wb").write(data)
    im = Image.open(p).convert("RGB")
    w, h = im.size
    r = cw / ch
    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((cw, ch), Image.LANCZOS)
    x, y = (n % cols) * cw, (n // cols) * ch
    sheet.paste(im, (x, y))
    d.rectangle([x + 6, y + 6, x + 190, y + 62], fill="black")
    d.text((x + 14, y + 10), f"{n+1}. {pid}", font=F, fill="white")
sheet.save(f"{OUT}/_contact_sheet_13b.jpg", quality=88)
print(f"contact sheet: {OUT}/_contact_sheet_13b.jpg")
for n, pid in enumerate(IDS):
    print(f"  {n+1}. {pid}")
