#!/usr/bin/env python3
"""Cari kandidat foto Pexels bertema dokumen/kantor hukum untuk artikel 14, lalu buat contact sheet berlabel.
Jalur cadangan (kunci API Pexels 401): r.jina.ai -> ambil id dari pexels-photo-<id> -> unduh dari CDN."""
import os, re, urllib.request, urllib.parse
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"}
QUERY = ["lawyer office desk documents", "law firm meeting team", "notary signing contract document",
         "justice scale law books office"]
ids = []
for q in QUERY:
    u = "https://r.jina.ai/https://www.pexels.com/search/" + urllib.parse.quote(q) + "/"
    try:
        r = urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=120).read().decode("utf-8", "ignore")
    except Exception as e:
        print(f"  lewat '{q}': {str(e)[:70]}")
        continue
    got = re.findall(r"pexels-photo-(\d+)", r)
    uniq = []
    for i in got:
        if i not in uniq:
            uniq.append(i)
    print(f"  {q}: {len(uniq)} id -> {uniq[:10]}")
    for i in uniq[:6]:
        if i not in ids:
            ids.append(i)

ids = ids[:12]
print("kandidat:", ids)

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)
ok = 0
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}/_kandidat14_{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 + 210, y + 62], fill="black")
    d.text((x + 14, y + 10), f"{n+1}. {pid}", font=F, fill="white")
    ok += 1
sheet.save(f"{OUT}/_contact_sheet_14.jpg", quality=88)
print(f"contact sheet: {OUT}/_contact_sheet_14.jpg ({ok} foto)")
for n, pid in enumerate(ids):
    print(f"  {n+1}. {pid}")
