#!/usr/bin/env python3
"""Ganti thumbnail bertulisan dengan foto Pexels asli untuk artikel #9120 & #9122."""
import base64, json, os, time, urllib.request, urllib.error
from PIL import Image

S = "https://studiosoft.id"
AUTH = base64.b64encode(b"bambangbot:q26r RePo BVy6 pwU2 F3z7 ouyl").decode()
OUT = "/home/mantapman/.hermes/profiles/atun/workspace/ss_pexels_coba"

PILIHAN = [
    {"post": 9120, "foto": 6476578, "nama": "jasa-maintenance-wordpress-surabaya.webp",
     "alt": "Monitor komputer menampilkan halaman website di meja kerja",
     "judul": "Maintenance WordPress - monitor dan website"},
    {"post": 9122, "foto": 6986455, "nama": "jasa-google-ads-surabaya.webp",
     "alt": "Laptop menampilkan halaman hasil pencarian dan kampanye iklan online",
     "judul": "Jasa Google Ads Surabaya - kampanye iklan online"},
]
TARGET = (1000, 567)  # sama dengan gambar artikel StudioSoft lain


def api(path, method="GET", data=None, raw=None, ctype=None, extra=None):
    h = {"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0"}
    body = None
    if data is not None:
        body = json.dumps(data).encode(); h["Content-Type"] = "application/json"
    elif raw is not None:
        body = raw; h["Content-Type"] = ctype
    if extra:
        h.update(extra)
    r = urllib.request.Request(S + path, data=body, headers=h, method=method)
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=180) as x:
                return x.status, json.loads(x.read())
        except urllib.error.HTTPError as e:
            return e.code, e.read().decode()[:250]
        except Exception:
            time.sleep(5)
    return 0, "gagal"


for p in PILIHAN:
    src = os.path.join(OUT, f"{p['foto']}.jpg")
    im = Image.open(src).convert("RGB")
    tw, th = TARGET
    w, h = im.size
    rasio = tw / th
    if w / h > rasio:
        nw = int(h * rasio); im = im.crop(((w - nw) // 2, 0, (w - nw) // 2 + nw, h))
    else:
        nh = int(w / rasio); im = im.crop((0, (h - nh) // 2, w, (h - nh) // 2 + nh))
    im = im.resize(TARGET, Image.LANCZOS)
    f = os.path.join(OUT, p["nama"])
    im.save(f, "WEBP", quality=90)
    print(f"\n=== post #{p['post']} ← pexels {p['foto']} ({im.size[0]}x{im.size[1]}, {os.path.getsize(f)//1024} KB)")

    st, med = api("/wp-json/wp/v2/media", "POST", raw=open(f, "rb").read(), ctype="image/webp",
                  extra={"Content-Disposition": f'attachment; filename="{p["nama"]}"'})
    if st not in (201, 200):
        print("   GAGAL unggah:", st, str(med)[:200]); continue
    mid = med["id"]
    api(f"/wp-json/wp/v2/media/{mid}", "POST", {"alt_text": p["alt"], "title": p["judul"]})
    print(f"   media baru #{mid}")
    # featured_media 2x (Yoast og:image tertinggal 1 save)
    for i in (1, 2):
        st2, _ = api(f"/wp-json/wp/v2/posts/{p['post']}", "POST", {"featured_media": mid})
        print(f"   set featured ({i}x): HTTP {st2}")
    st3, cek = api(f"/wp-json/wp/v2/posts/{p['post']}?context=edit&_fields=featured_media,link,status,date")
    print(f"   verifikasi: featured_media={cek.get('featured_media')} | status={cek.get('status')} | {cek.get('date')}")

print("\n=== gambar lama (bertulisan) ===")
for mid in (9119, 9121):
    st, r = api(f"/wp-json/wp/v2/media/{mid}?force=true", "DELETE")
    print(f"   media #{mid} → HTTP {st} (dihapus permanen dari pustaka)")
