#!/usr/bin/env python3
"""TSLaw: cari kandidat foto Pexels bertema dokumen tanah / kantor hukum."""
import os, re, urllib.parse, urllib.request
from PIL import Image, ImageDraw

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

QUERY = {
    "tanah": "land certificate property document",
    "notaris": "notary public signing document office",
}
kandidat = {}
for label, q in QUERY.items():
    try:
        md = urllib.request.urlopen(urllib.request.Request(
            f"https://r.jina.ai/https://www.pexels.com/search/{urllib.parse.quote(q)}/", headers=UA),
            timeout=120).read().decode("utf-8", "replace")
    except Exception as e:
        print(f"  {label}: gagal buka pencarian {str(e)[:60]}")
        continue
    ids = []
    for m in re.finditer(r"pexels-photo-(\d{4,})", md):
        if m.group(1) not in ids:
            ids.append(m.group(1))
    kandidat[label] = ids[:6]
    print(f"  {label} ({q}): {ids[:6]}")

for label, ids in kandidat.items():
    for i, pid in enumerate(ids):
        try:
            u = f"https://images.pexels.com/photos/{pid}/pexels-photo-{pid}.jpeg?auto=compress&cs=tinysrgb&w=1200"
            data = urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=90).read()
            p = f"{OUT}/{label}_{i}_{pid}.jpg"
            open(p, "wb").write(data)
            im = Image.open(p).convert("RGB")
            tw, th = 460, 260
            w, h = im.size
            r = tw / th
            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)))
            im.resize((tw, th), Image.LANCZOS).save(p.replace(".jpg", "_kecil.jpg"), quality=85)
            print(f"     {pid} ok ({os.path.getsize(p)//1024} KB)")
        except Exception as e:
            print(f"     {pid} gagal {str(e)[:50]}")

for label, ids in kandidat.items():
    baris = [Image.open(f"{OUT}/{label}_{i}_{ids[i]}_kecil.jpg") for i in range(len(ids))
             if os.path.exists(f"{OUT}/{label}_{i}_{ids[i]}_kecil.jpg")]
    if not baris:
        continue
    lembar = Image.new("RGB", (460 * 3, (260 + 22) * 2), (255, 255, 255))
    d = ImageDraw.Draw(lembar)
    for i, im in enumerate(baris):
        x, y = (i % 3) * 460, (i // 3) * (260 + 22)
        lembar.paste(im, (x, y))
        d.text((x + 6, y + 262), ids[i], fill=(0, 0, 0))
    lembar.save(f"{OUT}/lembar_{label}.png")
    print(f"  lembar_{label}.png siap")
