#!/usr/bin/env python3
"""TSLaw: cari foto Pexels untuk artikel sengketa tanah."""
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"
os.makedirs(OUT, exist_ok=True)
q = "property document land certificate"
md = urllib.request.urlopen(urllib.request.Request(
    f"https://r.jina.ai/https://www.pexels.com/search/{urllib.parse.quote(q)}/", headers=UA), timeout=90
).read().decode("utf-8", "replace")
ids = []
for m in re.finditer(r"pexels-photo-(\d{4,})", md):
    if m.group(1) not in ids:
        ids.append(m.group(1))
ids = ids[:6]
print("kandidat:", ids)

kecil = []
for i, pid in enumerate(ids):
    try:
        u = f"https://images.pexels.com/photos/{pid}/pexels-photo-{pid}.jpeg?auto=compress&cs=tinysrgb&w=900"
        data = urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=60).read()
        p = f"{OUT}/tanah_{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)
        kecil.append((pid, Image.open(p.replace(".jpg", "_kecil.jpg"))))
    except Exception as e:
        print(f"  {pid} gagal {str(e)[:40]}")

if kecil:
    lembar = Image.new("RGB", (460 * 3, (260 + 22) * 2), (255, 255, 255))
    d = ImageDraw.Draw(lembar)
    for i, (pid, im) in enumerate(kecil):
        x, y = (i % 3) * 460, (i // 3) * (260 + 22)
        lembar.paste(im, (x, y))
        d.text((x + 6, y + 262), pid, fill=(0, 0, 0))
    lembar.save(f"{OUT}/lembar_tanah.jpg", quality=88)
    print("lembar_tanah.jpg siap")
