#!/usr/bin/env python3
"""TSLaw artikel 7: cari foto Pexels via jalur cadangan (r.jina.ai -> ID -> CDN), buat contact sheet."""
import os, re, urllib.request
from PIL import Image

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 = ["trademark", "brand-name-document", "intellectual-property", "legal-contract-signing"]

ids = []
for q in QUERIES:
    url = f"https://r.jina.ai/https://www.pexels.com/search/{q}/"
    try:
        txt = 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,})", txt)
    uniq = list(dict.fromkeys(found))
    print(f"{q}: {len(uniq)} id -> {uniq[:12]}")
    ids += [(q, i) for i in uniq[:6]]

print(f"\ntotal kandidat: {len(ids)}")
thumbs = []
for q, pid in ids:
    u = f"https://images.pexels.com/photos/{pid}/pexels-photo-{pid}.jpeg?auto=compress&cs=tinysrgb&w=400"
    try:
        data = urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=90).read()
        p = f"{OUT}/_kandidat_{pid}.jpg"
        open(p, "wb").write(data)
        thumbs.append((pid, p, q))
    except Exception as e:
        print(f"  lewat {pid}: {str(e)[:50]}")

if thumbs:
    cols, cw, ch = 5, 320, 182
    rows = (len(thumbs) + cols - 1) // cols
    sheet = Image.new("RGB", (cols * cw, rows * ch), "white")
    for n, (pid, p, q) in enumerate(thumbs):
        im = Image.open(p).convert("RGB")
        w, h = im.size
        r = cw / ch
        im = im.crop(((w - int(h * r)) // 2, 0, (w - int(h * r)) // 2 + int(h * r), h)) if w / h > r else \
             im.crop((0, (h - int(w / r)) // 2, w, (h - int(w / r)) // 2 + int(w / r)))
        sheet.paste(im.resize((cw, ch), Image.LANCZOS), ((n % cols) * cw, (n // cols) * ch))
    sheet.save(f"{OUT}/_contact_sheet_7.jpg", quality=85)
    print(f"\ncontact sheet: {OUT}/_contact_sheet_7.jpg")
    print("urutan ID:")
    for n, (pid, p, q) in enumerate(thumbs):
        print(f"  {n+1:>2}. {pid}  ({q})")
