#!/usr/bin/env python3
"""Pasang gambar unggulan untuk 4 artikel TSLaw yang belum punya, memakai gambar pustaka yang belum terpakai.

Pilihan gambar disesuaikan tema artikel, dan dipastikan belum dipakai artikel lain supaya tidak berulang.
"""
import base64, json, re, time, urllib.error, urllib.request

SITUS = "https://www.tslaw.id"
AUTH = base64.b64encode(b"bambangbot:EFKm EYGx VQCP Y9go ncPr uM2Y").decode()
H = {"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0", "Content-Type": "application/json"}

PASANG = [
    (3574, 3688, "Ilustrasi konsultan hukum perusahaan di Surabaya"),
    (3570, 3716, "Ilustrasi memilih pengacara terbaik di Surabaya"),
    (3566, 2938, "Ilustrasi rincian biaya jasa hukum"),
    (3559, 2883, "Ilustrasi hukum bisnis untuk perusahaan"),
]


def rest(path, method="GET", data=None):
    body = json.dumps(data).encode() if data is not None else None
    r = urllib.request.Request(f"{SITUS}{path}", data=body, headers=H, method=method)
    for i in range(3):
        try:
            with urllib.request.urlopen(r, timeout=120) as x:
                return x.status, json.loads(x.read())
        except urllib.error.HTTPError as e:
            return e.code, e.read().decode()[:200]
        except Exception:
            time.sleep(4)
    return 0, "gagal"


print("=== cek gambar yang akan dipakai ===")
for pid, mid, alt in PASANG:
    st, m = rest(f"/wp-json/wp/v2/media/{mid}?_fields=id,source_url,media_details")
    nama = (m.get("source_url") or "?").split("/")[-1] if isinstance(m, dict) else "?"
    uk = (m.get("media_details") or {}).get("width") if isinstance(m, dict) else "?"
    print(f"   #{pid} ← media #{mid} ({uk}px) {nama[:56]}")
    time.sleep(0.3)

print("\n=== memasang ===")
for pid, mid, alt in PASANG:
    st, d = rest(f"/wp-json/wp/v2/media/{mid}", "POST", {"alt_text": alt})
    st2, p = rest(f"/wp-json/wp/v2/posts/{pid}", "POST", {"featured_media": mid})
    time.sleep(0.6)
    st3, cek = rest(f"/wp-json/wp/v2/posts/{pid}?_fields=id,featured_media,link")
    ok = isinstance(cek, dict) and cek.get("featured_media") == mid
    print(f"   {'✅' if ok else '❌'} #{pid} ← media {mid} (HTTP {st2}) · sekarang {cek.get('featured_media') if isinstance(cek, dict) else '?'}")

print("\n=== verifikasi akhir seluruh artikel ===")
posts, page = [], 1
while True:
    st, d = rest(f"/wp-json/wp/v2/posts?per_page=100&page={page}&status=publish&_fields=id,featured_media")
    if not isinstance(d, list) or not d:
        break
    posts += d
    if len(d) < 100:
        break
    page += 1
tanpa = [p["id"] for p in posts if not p.get("featured_media")]
pakai = {}
for p in posts:
    if p.get("featured_media"):
        pakai.setdefault(p["featured_media"], []).append(p["id"])
ulang = {k: v for k, v in pakai.items() if len(v) > 1}
print(f"   artikel: {len(posts)} · tanpa gambar unggulan: {len(tanpa)} {tanpa}")
print(f"   gambar unik: {len(pakai)} · dipakai berulang: {len(ulang)} {ulang if ulang else ''}")
