#!/usr/bin/env python3
"""TSLaw 17 Okt: cari kandidat foto Pexels bertema notaris/dokumen akta lewat jalur cadangan
(kunci API Pexels 401): scrape halaman pencarian via r.jina.ai -> ID -> CDN images.pexels.com,
potong 1000x567 webp, buat lembar kontak, lalu cek pustaka media agar tidak memakai foto ganda."""
import base64, json, os, re, urllib.request, urllib.error
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"
DOM = "tslaw.id"
AUTH = base64.b64encode(b"bambangbot:EFKm EYGx VQCP Y9go ncPr uM2Y").decode()
Q = ["notary public signing document", "notary stamp seal", "signing legal contract documents", "land certificate property documents"]

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
    found = re.findall(r"pexels-photo-(\d{4,})", html)
    uniq = []
    for i in found:
        if i not in uniq:
            uniq.append(i)
    print(f"  {q}: {len(uniq)} id -> {uniq[:12]}")
    ids += uniq[:12]

seen, pilih = set(), []
for i in ids:
    if i not in seen:
        seen.add(i)
        pilih.append(i)
pilih = pilih[:16]
print(f"  kandidat total: {len(pilih)} {pilih}")


def ambil(pid):
    src = f"{OUT}/_kandidat19_{pid}.jpg"
    if not os.path.exists(src):
        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())
    return Image.open(src).convert("RGB")


kotak, ok = [], []
for pid in pilih:
    try:
        im = ambil(pid)
    except Exception as e:
        print(f"  {pid}: gagal unduh {type(e).__name__}")
        continue
    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))
sheet = f"{OUT}/contact_sheet_19.jpg"
c.save(sheet)
print(f"  lembar kontak: {sheet} {c.size} | urut: {ok}")

h = {"Authorization": f"Basic {AUTH}", **UA}
semua = []
for off in (0, 100, 200, 300):
    try:
        r = urllib.request.Request(f"https://{DOM}/wp-json/wp/v2/media?per_page=100&offset={off}&_fields=id,source_url,title", headers=h)
        with urllib.request.urlopen(r, timeout=180) as x:
            p = json.loads(x.read())
    except urllib.error.HTTPError as e:
        print(f"  media offset {off}: HTTP {e.code}")
        break
    if not p:
        break
    semua += p
print(f"  media pustaka: {len(semua)}")
for m in semua:
    if "pexels" in m["source_url"]:
        print("   nama asli pexels:", m["id"], m["source_url"])
