#!/usr/bin/env python3
"""Penyesuaian akhir thumbnail #9120 & #9122:
   #9120 (maintenance) ← Pexels 1181449 (laptop menampilkan website)
   #9122 (Google Ads)  ← media 9123 yang sudah ada (Pexels 6476578, dashboard Ad Spend)
   media 9125 (tidak dipakai) dihapus."""
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"


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"


# 1. siapkan + unggah foto laptop-website
im = Image.open(os.path.join(OUT, "1181449.jpg")).convert("RGB")
tw, th = 1000, 567
w, h = im.size
r = tw / th
im = im.crop(((w - int(h * r)) // 2, 0, (w - int(h * r)) // 2 + int(h * r), h)) if w / h > r else \
     im.crop((0, (h - int(w / r)) // 2, w, (h - int(w / r)) // 2 + int(w / r)))
im = im.resize((tw, th), Image.LANCZOS)
f = os.path.join(OUT, "jasa-maintenance-wordpress-surabaya.webp")
im.save(f, "WEBP", quality=90)
print(f"file: {f} ({os.path.getsize(f)//1024} KB, {im.size[0]}x{im.size[1]})")

st, med = api("/wp-json/wp/v2/media", "POST", raw=open(f, "rb").read(), ctype="image/webp",
              extra={"Content-Disposition": 'attachment; filename="jasa-maintenance-wordpress-surabaya.webp"'})
print("unggah media:", st, med.get("id") if isinstance(med, dict) else str(med)[:120])
mid = med["id"]
api(f"/wp-json/wp/v2/media/{mid}", "POST",
    {"alt_text": "Laptop menampilkan halaman website yang sedang dikelola", "title": "Maintenance WordPress - laptop dan website"})

# 2. pasang featured (2x karena Yoast og:image tertinggal satu save)
for post, media, ket in ((9120, mid, "foto laptop+website"), (9122, 9123, "dashboard Ad Spend (media lama)")):
    for i in (1, 2):
        st2, _ = api(f"/wp-json/wp/v2/posts/{post}", "POST", {"featured_media": media})
    st3, cek = api(f"/wp-json/wp/v2/posts/{post}?context=edit&_fields=featured_media,date,status,link")
    print(f"  #{post} → media {media} ({ket}) | HTTP {st2} | verifikasi featured={cek.get('featured_media')} status={cek.get('status')}")

# 3. hapus media yang tidak terpakai
st, _ = api("/wp-json/wp/v2/media/9125?force=true", "DELETE")
print("hapus media #9125 (tidak dipakai):", st)

# 4. ringkasan akhir
print("\n=== keadaan akhir ===")
for post in (9120, 9122):
    _, p = api(f"/wp-json/wp/v2/posts/{post}?context=edit&_fields=id,title,link,status,date,featured_media,meta")
    _, m = api(f"/wp-json/wp/v2/media/{p['featured_media']}?_fields=id,source_url,alt_text,media_details")
    print(f"  #{post} {p['title']['rendered'][:52]}")
    print(f"      tayang {p['date']} | status {p['status']}")
    print(f"      gambar media #{m['id']} {m['media_details'].get('width')}x{m['media_details'].get('height')}")
    print(f"      file   {m['source_url']}")
    print(f"      alt    {m['alt_text']}")
