#!/usr/bin/env python3
"""TSLaw 18 Okt: cari kandidat foto Pexels bertema dokumen pajak/meja akuntan lewat jalur cadangan
(kunci API Pexels 401): scrape halaman pencarian via r.jina.ai -> ID -> CDN images.pexels.com,
buat lembar kontak 1000x567, 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 = ["accountant calculator tax documents",
     "tax form paperwork desk",
     "auditor reviewing financial documents",
     "bookkeeping ledger calculator desk"]

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}/_kandidat20_{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.45)
        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_20.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, 400):
    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
dipakai = set(re.findall(r"pexels-photo-(\d+)", " ".join(m["source_url"] for m in semua)))
print(f"  media pustaka: {len(semua)} | id pexels sudah dipakai: {sorted(dipakai)}")
