#!/usr/bin/env python3
"""Cari kandidat foto Pexels (jalur cadangan r.jina.ai -> ID -> CDN) + contact sheet."""
import os, re, json, urllib.request, urllib.error

UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36"}
OUT = "/home/mantapapman/.hermes/profiles/atun/workspace/tslaw_listikel"
OUT = "/home/mantapman/.hermes/profiles/atun/workspace/tslaw_listikel"
os.makedirs(OUT, exist_ok=True)

queries = [
    "law-office-documents-gavel",
    "courtroom-documents-lawyer-desk",
    "person-phone-social-media-typing",
    "legal-documents-signing-pen",
]
ids = []
for q in queries:
    url = f"https://r.jina.ai/https://www.pexels.com/search/{q}/"
    try:
        d = urllib.request.urlopen(urllib.request.Request(url, headers=UA), timeout=120).read().decode("utf-8", "ignore")
    except Exception as e:
        print(f"  GAGAL {q}: {str(e)[:80]}"); continue
    found = re.findall(r"pexels-photo-(\d{4,})", d)
    uniq = []
    for i in found:
        if i not in uniq:
            uniq.append(i)
    print(f"  {q}: {len(uniq)} id -> {uniq[:12]}")
    ids += uniq[:12]

seen, cand = set(), []
for i in ids:
    if i not in seen:
        seen.add(i); cand.append(i)
print(f"\n{len(cand)} kandidat unik")

ok = []
for i in cand:
    u = f"https://images.pexels.com/photos/{i}/pexels-photo-{i}.jpeg?auto=compress&cs=tinysrgb&w=900"
    f = f"{OUT}/_kand_{i}.jpg"
    if not os.path.exists(f):
        try:
            open(f, "wb").write(urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=90).read())
        except Exception as e:
            print(f"  gagal unduh {i}: {str(e)[:50]}"); continue
    ok.append((i, f))
print(f"{len(ok)} kandidat terunduh")

from PIL import Image, ImageDraw, ImageFont
try:
    font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 22)
except Exception:
    font = ImageFont.load_default()
cols, cw, ch = 4, 320, 200
rows = (len(ok) + cols - 1) // cols
sheet = Image.new("RGB", (cols * cw, rows * (ch + 28)), "white")
dr = ImageDraw.Draw(sheet)
for n, (i, f) in enumerate(ok):
    try:
        im = Image.open(f).convert("RGB")
    except Exception:
        continue
    w, h = im.size
    r = cw / ch
    if w / h > r:
        nw = int(h * r); x0 = (w - nw) // 2; im = im.crop((x0, 0, x0 + nw, h))
    else:
        nh = int(w / r); y0 = (h - nh) // 2; im = im.crop((0, y0, w, y0 + nh))
    im = im.resize((cw, ch), Image.LANCZOS)
    x = (n % cols) * cw; y = (n // cols) * (ch + 28)
    sheet.paste(im, (x, y))
    dr.text((x + 6, y + ch + 3), f"{i}", fill="black", font=font)
sheet.save(f"{OUT}/_contact_sheet.jpg", quality=88)
print(f"contact sheet: {OUT}/_contact_sheet.jpg  {sheet.size}")
