#!/usr/bin/env python3
"""Gambar unggulan (1000x567 WebP) untuk draf #9609 — pola sama seperti artikel terjadwal lain.

Pakai: python3 ss_artikel_situs_lambat_media.py        (uji)
       python3 ss_artikel_situs_lambat_media.py --go  (kerjakan)
"""
import base64, json, os, sys, time, urllib.request

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
S = "https://studiosoft.id"
PID = 9609
GO = "--go" in sys.argv
H = {"Authorization": "Basic " + base64.b64encode(b"bambangbot:q26r RePo BVy6 pwU2 F3z7 ouyl").decode(),
     "User-Agent": "Mozilla/5.0"}
HJ = {**H, "Content-Type": "application/json"}


def rest(p, method="GET", data=None):
    body = json.dumps(data).encode() if data is not None else None
    r = urllib.request.Request(S + p, data=body, headers=HJ, method=method)
    try:
        with urllib.request.urlopen(r, timeout=180) as x:
            return json.loads(x.read())
    except Exception as e:
        return {"err": str(e)[:80]}


def buat_gambar(judul, berkas):
    from PIL import Image, ImageDraw, ImageFont
    F = os.path.expanduser("~/.fonts")
    f = lambda n, s: ImageFont.truetype(os.path.join(F, n), s)
    NAVY, BIRU, ABU = (11, 31, 58), (37, 99, 235), (100, 116, 139)
    W, Hh, PAD = 1000, 567, 62

    def bungkus(t, font, maks):
        baris, kini = [], ""
        for k in t.split():
            c = (kini + " " + k).strip()
            if font.getlength(c) <= maks:
                kini = c
            else:
                baris.append(kini)
                kini = k
        if kini:
            baris.append(kini)
        return baris

    img = Image.new("RGB", (W, Hh), (255, 255, 255))
    dr = ImageDraw.Draw(img)
    dr.rectangle([0, 0, W, 12], fill=BIRU)
    dr.rectangle([W - 300, Hh - 300, W, Hh], fill=(240, 245, 255))
    for i in range(3):
        dr.ellipse([W - 230 + i * 26, Hh - 210 + i * 26, W - 60, Hh - 40], outline=BIRU, width=2)
    dr.text((PAD, 62), "STUDIOSOFT", font=f("Poppins-SemiBold.ttf", 24), fill=BIRU)
    dr.text((PAD, 96), "Catatan digital marketing", font=f("Poppins-Regular.ttf", 20), fill=ABU)
    y = 175
    for b in bungkus(judul, f("Poppins-Bold.ttf", 44), W - 360):
        dr.text((PAD, y), b, font=f("Poppins-Bold.ttf", 44), fill=NAVY)
        print(f"      baris y={y}: lebar {f('Poppins-Bold.ttf', 44).getlength(b):.0f}px · {b}")
        y += 56
    dr.rectangle([PAD, Hh - 96, PAD + 74, Hh - 92], fill=BIRU)
    dr.text((PAD, Hh - 78), "studiosoft.id", font=f("Poppins-SemiBold.ttf", 23), fill=NAVY)
    img.save(berkas, "WEBP", quality=92, method=6)
    return img.size


d = rest(f"/wp-json/wp/v2/posts/{PID}?context=edit&_fields=title,slug,status,featured_media")
print(f"#{PID} status={d.get('status')} gambar_sekarang={d.get('featured_media')}")
judul = "Situs Lambat di Ponsel: 9 Penyebab"
berkas = f"{WS}/ss_feat_situs-lambat-di-ponsel.webp"
print("   menggambar:")
print("   ukuran:", buat_gambar(judul, berkas), "|", round(os.path.getsize(berkas) / 1024, 1), "KB")

if not GO:
    print("\n(uji, pakai --go untuk unggah + pasang)")
    sys.exit(0)

data = open(berkas, "rb").read()
hh = {**H, "Content-Type": "image/webp",
      "Content-Disposition": 'attachment; filename="ss_feat_situs-lambat-di-ponsel.webp"'}
r = urllib.request.Request(f"{S}/wp-json/wp/v2/media", data=data, headers=hh, method="POST")
with urllib.request.urlopen(r, timeout=300) as x:
    med = json.loads(x.read())
print("   media:", med["id"], med["source_url"])
rest(f"/wp-json/wp/v2/media/{med['id']}", "POST", {"alt_text": "Situs lambat di ponsel", "title": judul})
hasil = rest(f"/wp-json/wp/v2/posts/{PID}", "POST", {"featured_media": med["id"]})
time.sleep(1)
v = rest(f"/wp-json/wp/v2/posts/{PID}?context=edit&_fields=status,featured_media,slug")
print("   baca balik: status=%s gambar=%s slug=%s" % (v.get("status"), v.get("featured_media"), v.get("slug")))
m = rest(f"/wp-json/wp/v2/media/{med['id']}?_fields=alt_text,media_details")
print("   alt:", m.get("alt_text"), "| ukuran:",
      (m.get("media_details") or {}).get("width"), "x", (m.get("media_details") or {}).get("height"))
