#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Pasang gambar unggulan (1000x567 WebP) pada 7 artikel StudioSoft yang belum punya, lalu jadikan draf.

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

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
S = "https://studiosoft.id"
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"}
GO = "--go" in sys.argv

PID = [9315, 9319, 9322, 9332, 9335, 9393, 9402]


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)[:60]}


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)
        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


print(f"{'#id':<7}{'kata':>6}{'gambar':>9}  judul")
for pid in PID:
    d = rest(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=title,slug,status,featured_media,date")
    judul = re.sub("<[^>]+>", "", d["title"]["raw"])
    kata = "-"
    print(f"{pid:<7}{str(d.get('featured_media') or '-'):>8}  {d['status']:<8}{judul[:52]}")
    if not GO:
        continue
    berkas = f"{WS}/ss_feat_{d['slug'][:38]}.webp"
    ukuran = buat_gambar(judul, berkas)
    data = open(berkas, "rb").read()
    hh = {**H, "Content-Type": "image/webp",
          "Content-Disposition": f'attachment; filename="{os.path.basename(berkas)}"'}
    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())
    rest(f"/wp-json/wp/v2/media/{med['id']}", "POST", {"alt_text": judul, "title": judul[:90]})
    rest(f"/wp-json/wp/v2/posts/{pid}", "POST", {"featured_media": med["id"], "status": "draft"})
    v = rest(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=status,featured_media")
    print(f"        → media #{med['id']} {ukuran[0]}x{ukuran[1]} · status {v.get('status')} · "
          f"gambar {v.get('featured_media')}")
    time.sleep(0.6)

if not GO:
    print("\n(uji — pakai --go untuk memasang gambar + jadikan draf)")
