#!/usr/bin/env python3
"""TSLaw: cari foto Pexels (jalur jina scrape) untuk artikel konsultan pendirian PT/CV."""
import os, re, urllib.parse, urllib.request
from PIL import Image

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)

ids = []
for q in ["business meeting contract documents", "signing contract lawyer office"]:
    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"  {q}: gagal {str(e)[:70]}")
        continue
    baru = [m.group(1) for m in re.finditer(r"pexels-photo-(\d{4,})", md)]
    print(f"=== {q}: {len(set(baru))} id ===  {list(dict.fromkeys(baru))[:12]}")
    ids += [i for i in baru if i not in ids]

ids = list(dict.fromkeys(ids))[:12]
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}/pt_{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)))
        p2 = p.replace(".jpg", "_kecil.jpg")
        im.resize((tw, th), Image.LANCZOS).save(p2, quality=85)
        kecil.append((pid, p2))
    except Exception as e:
        print(f"  {pid} gagal {str(e)[:40]}")

if kecil:
    baris = (len(kecil) + 2) // 3
    from PIL import ImageDraw
    lembar = Image.new("RGB", (460 * 3, (260 + 22) * baris), (255, 255, 255))
    d = ImageDraw.Draw(lembar)
    for i, (pid, p2) in enumerate(kecil):
        x, y = (i % 3) * 460, (i // 3) * (260 + 22)
        lembar.paste(Image.open(p2), (x, y))
        d.text((x + 6, y + 262), f"{i}: {pid}", fill=(0, 0, 0))
    lembar.save(f"{OUT}/lembar_pt.jpg", quality=88)
    print(f"\nlembar_pt.jpg siap: {lembar.size} -> {OUT}/lembar_pt.jpg")
    for i, (pid, _) in enumerate(kecil):
        print(f"  {i}: {pid}")
