#!/usr/bin/env python3
"""TSLaw artikel #15: pilih foto Pexels lewat jalur cadangan (r.jina.ai -> ID -> CDN),
buat contact sheet supaya bisa diperiksa sebelum dipotong 1000x567."""
import os, re, urllib.request, urllib.error, urllib.parse

OUT = "/home/mantapman/.hermes/profiles/atun/workspace/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"}
QUERIES = ["debt collection letter", "legal documents desk", "signed contract paperwork", "lawyer office desk documents"]

kandidat = []
for q in QUERIES:
    u = "https://r.jina.ai/https://www.pexels.com/search/" + urllib.parse.quote(q) + "/"
    try:
        html = urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=120).read().decode("utf-8", "ignore")
    except Exception as e:
        print(f"  GAGAL {q}: {str(e)[:80]}")
        continue
    ids = []
    for m in re.finditer(r"pexels-photo-(\d{4,})", html):
        if m.group(1) not in ids:
            ids.append(m.group(1))
    print(f"  {q}: {len(ids)} id -> {ids[:8]}")
    for i in ids[:8]:
        if i not in kandidat:
            kandidat.append(i)

print(f"\ntotal kandidat: {len(kandidat)}")

from PIL import Image, ImageDraw
thumbs = []
for cid in kandidat[:20]:
    url = f"https://images.pexels.com/photos/{cid}/pexels-photo-{cid}.jpeg?auto=compress&cs=tinysrgb&w=800"
    f = f"{OUT}/_kand_{cid}.jpg"
    if not os.path.exists(f):
        try:
            data = urllib.request.urlopen(urllib.request.Request(url, headers=UA), timeout=90).read()
            open(f, "wb").write(data)
        except Exception as e:
            print(f"  gagal unduh {cid}: {str(e)[:60]}")
            continue
    try:
        im = Image.open(f).convert("RGB")
    except Exception as e:
        print(f"  gagal buka {cid}: {str(e)[:60]}")
        continue
    thumbs.append((cid, im))

if thumbs:
    cols, cw, ch = 5, 320, 200
    rows = (len(thumbs) + cols - 1) // cols
    sheet = Image.new("RGB", (cols * cw, rows * (ch + 22)), (20, 20, 30))
    d = ImageDraw.Draw(sheet)
    for k, (cid, im) in enumerate(thumbs):
        x, y = (k % cols) * cw, (k // cols) * (ch + 22)
        im2 = im.copy()
        im2.thumbnail((cw - 8, ch - 8))
        sheet.paste(im2, (x + 4, y + 4))
        d.text((x + 6, y + ch + 2), f"{cid}  {im.size[0]}x{im.size[1]}", fill=(240, 240, 240))
    p = f"{OUT}/contact_sheet_15.jpg"
    sheet.save(p, "JPEG", quality=82)
    print(f"contact sheet: {p} ({os.path.getsize(p)//1024} KB) - {len(thumbs)} kandidat")
