#!/usr/bin/env python3
"""TSLaw 17 Okt putaran 2: cari foto bertema stempel/dokumen resmi (notaris, PPAT).
Jalur cadangan Pexels: scrape lewat r.jina.ai -> ID -> CDN. Simpan lembar kontak."""
import os, re, urllib.request
from PIL import Image, ImageDraw, ImageFont

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"
Q = ["notary seal stamp paper", "rubber stamp document approval", "stamping official document", "property certificate land title document"]
PAKAI = {"7841410", "34862508", "6326287", "7841818", "261621", "7693692", "8872719", "8815843",
         "5833238", "7876197", "7504780", "6538440", "7876093", "6077447", "6077665", "39356214"}

ids = []
for q in Q:
    u = "https://r.jina.ai/https://www.pexels.com/search/" + q.replace(" ", "%20") + "/"
    try:
        with urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=120) as x:
            html = x.read().decode("utf-8", "replace")
    except Exception as e:
        print(f"  {q}: GAGAL {type(e).__name__}")
        continue
    uniq = []
    for i in re.findall(r"pexels-photo-(\d{4,})", html):
        if i not in uniq:
            uniq.append(i)
    print(f"  {q}: {uniq[:12]}")
    ids += uniq[:12]

pilih, seen = [], set()
for i in ids:
    if i in PAKAI or i in seen:
        continue
    seen.add(i)
    pilih.append(i)
pilih = pilih[:14]
print("  kandidat baru:", pilih)

kotak, ok = [], []
for pid in pilih:
    src = f"{OUT}/_k2_{pid}.jpg"
    if not os.path.exists(src):
        try:
            u = f"https://images.pexels.com/photos/{pid}/pexels-photo-{pid}.jpeg?auto=compress&cs=tinysrgb&w=1200"
            open(src, "wb").write(urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=90).read())
        except Exception as e:
            print(f"  {pid}: gagal unduh {type(e).__name__}")
            continue
    im = Image.open(src).convert("RGB")
    w, h = im.size
    tw, th = 400, 227
    r = tw / th
    if w / h > r:
        cw = int(h * r); x0 = (w - cw) // 2
        im2 = im.crop((x0, 0, x0 + cw, h))
    else:
        ch = int(w / r); y0 = int((h - ch) * 0.35)
        im2 = im.crop((0, y0, w, y0 + ch))
    kotak.append((pid, im2.resize((tw, th), Image.LANCZOS)))
    ok.append(pid)

kol = 4
bar = (len(kotak) + kol - 1) // kol
c = Image.new("RGB", (kol * 400, bar * 253), "white")
d = ImageDraw.Draw(c)
try:
    ft = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 18)
except Exception:
    ft = ImageFont.load_default()
for n, (pid, im) in enumerate(kotak):
    x = (n % kol) * 400
    y = (n // kol) * 253
    d.text((x + 6, y + 4), f"{n+1}. {pid}", fill="black", font=ft)
    c.paste(im, (x, y + 26))
c.save(f"{OUT}/contact_sheet_19b.jpg")
print(f"  lembar kontak: {OUT}/contact_sheet_19b.jpg {c.size} | urut: {ok}")
