#!/usr/bin/env python3
"""TSLaw artikel #15: uji potongan foto kandidat (1000x567) untuk diperiksa sebelum dipakai."""
import os, urllib.request
from PIL import Image

OUT = "/home/mantapman/.hermes/profiles/atun/workspace/tslaw_listikel"
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36"}
KAND = ["6538440", "7658310", "33936499", "7680324"]

for cid in KAND:
    src = f"{OUT}/_kand_{cid}.jpg"
    if not os.path.exists(src):
        u = f"https://images.pexels.com/photos/{cid}/pexels-photo-{cid}.jpeg?auto=compress&cs=tinysrgb&w=1600"
        open(src, "wb").write(urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=90).read())
    im = Image.open(src).convert("RGB")
    w, h = im.size
    r = 1000 / 567
    for tag, yb in (("a", 0.30), ("b", 0.55)):
        if w / h > r:
            cw = int(h * r); x0 = (w - cw) // 2
            c = im.crop((x0, 0, x0 + cw, h))
        else:
            ch = int(w / r); y0 = int((h - ch) * yb)
            c = im.crop((0, y0, w, y0 + ch))
        f = f"{OUT}/_uji_{cid}_{tag}.webp"
        c.resize((1000, 567), Image.LANCZOS).save(f, "WEBP", quality=80, method=6)
        print(f"  {cid} varian {tag} (ybias {yb}) -> {f} ({os.path.getsize(f)//1024} KB) sumber {w}x{h}")
