#!/usr/bin/env python3
"""Pasang featured image Pexels 10638213 ke artikel LEIT 4147 (bahasa-inggris-untuk-anak-metode-seru)."""
import base64, json, os, sys, io, urllib.request, urllib.error

WS = os.path.dirname(os.path.abspath(__file__))
SITE = "https://www.leitsurabaya.com"
AUTH = base64.b64encode(b"bambangbot:zibd dLIV xY8x onP9 39qL hiNr").decode()
HDR = {"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0"}

POST_ID = 4147
SLUG = "bahasa-inggris-untuk-anak-metode-seru"
PEXELS = "https://images.pexels.com/photos/10638213/pexels-photo-10638213.jpeg"
ALT = "Sekelompok anak membaca buku bersama saat belajar bahasa Inggris"
OUT = os.path.join(WS, "leit_featured_4147_raw.webp")


def req(method, path, data=None, headers=None, raw_body=None):
    h = dict(HDR)
    if headers:
        h.update(headers)
    body = raw_body if raw_body is not None else (json.dumps(data).encode() if data is not None else None)
    r = urllib.request.Request(SITE + path, data=body, headers=h, method=method)
    try:
        with urllib.request.urlopen(r, timeout=120) as resp:
            b = resp.read()
            return resp.status, (json.loads(b) if b[:1] in (b"{", b"[") else b[:200])
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode()[:400]


# 1. download + crop 16:9 → 1000x567 webp
print("1) download pexels…")
raw = urllib.request.urlopen(urllib.request.Request(PEXELS + "?auto=compress&cs=tinysrgb&w=2400",
                             headers={"User-Agent": "Mozilla/5.0"}), timeout=120).read()
print("   bytes:", len(raw))
from PIL import Image
im = Image.open(io.BytesIO(raw)).convert("RGB")
W, H = im.size
tw, th = 1000, 567
target = tw / th
if W / H > target:
    nw = int(H * target); im = im.crop(((W - nw) // 2, 0, (W - nw) // 2 + nw, H))
else:
    nh = int(W / target); im = im.crop((0, (H - nh) // 2, W, (H - nh) // 2 + nh))
im = im.resize((tw, th), Image.LANCZOS)
im.save(OUT, "WEBP", quality=90, method=6)
print("   saved:", OUT, os.path.getsize(OUT), "bytes", im.size)

# 2. upload ke WP media
print("2) upload ke WP media…")
fname = f"{SLUG}-pexels-1000x567.webp"
with open(OUT, "rb") as f:
    blob = f.read()
st, res = req("POST", "/wp-json/wp/v2/media", raw_body=blob, headers={
    "Content-Type": "image/webp",
    "Content-Disposition": f'attachment; filename="{fname}"',
})
print("   http", st)
if st not in (200, 201):
    print("   FAIL:", res); sys.exit(1)
mid = res["id"]
print("   media id", mid, res.get("source_url"))

# 3. alt text
st, res = req("POST", f"/wp-json/wp/v2/media/{mid}", data={"alt_text": ALT, "title": "Bahasa Inggris untuk Anak — Pexels 10638213"})
print("3) alt http", st, res.get("alt_text") if isinstance(res, dict) else res)

# 4. set featured_media pada post
st, res = req("POST", f"/wp-json/wp/v2/posts/{POST_ID}", data={"featured_media": mid})
print("4) set featured http", st, res.get("featured_media") if isinstance(res, dict) else res)

# 5. verify
st, res = req("GET", f"/wp-json/wp/v2/posts/{POST_ID}?_fields=id,link,featured_media")
print("5) verify post:", st, res)
st, res = req("GET", f"/wp-json/wp/v2/media/{mid}?_fields=id,alt_text,source_url,media_details")
md = res.get("media_details", {})
print("   verify media:", st, res.get("source_url"), md.get("width"), "x", md.get("height"), "| alt:", res.get("alt_text"))
