#!/usr/bin/env python3
"""Periksa gambar unggulan artikel TSC: punya #10134, artikel lain, dan isi pustaka media terbaru."""
import base64, importlib.util, json, re, time, urllib.error, urllib.request

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg", f"{WS}/cfg_tsc.py")
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
CFG = m.CFG
DOM = CFG["domain"]
AUTH = base64.b64encode(f"{CFG['user']}:{CFG['pass']}".encode()).decode()
UA = {"User-Agent": "Mozilla/5.0"}


def rest(path):
    h = {"Authorization": f"Basic {AUTH}", **UA}
    r = urllib.request.Request(f"https://{DOM}{path}", headers=h)
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=120) as x:
                return json.loads(x.read())
        except urllib.error.HTTPError as e:
            return {"err": e.code}
        except Exception:
            time.sleep(4)
    return {}


p = rest("/wp-json/wp/v2/posts/10134?context=edit&_fields=id,featured_media,link")
print(f"#10134 featured_media: {p.get('featured_media')}")

print("\n=== 8 artikel TSC terbaru dan gambar unggulannya ===")
d = rest("/wp-json/wp/v2/posts?per_page=8&orderby=date&order=desc&_fields=id,slug,featured_media,date")
for x in d if isinstance(d, list) else []:
    fm = x.get("featured_media")
    url = "-"
    if fm:
        mm = rest(f"/wp-json/wp/v2/media/{fm}?_fields=source_url")
        url = mm.get("source_url", "-")[-70:]
    print(f"  #{x['id']:<6} fm={fm:<7} {url}")

print("\n=== 12 gambar terbaru di pustaka media ===")
med = rest("/wp-json/wp/v2/media?per_page=12&orderby=date&order=desc&_fields=id,title,source_url,date")
for x in med if isinstance(med, list) else []:
    judul = re.sub(r"<[^>]+>", "", str(x.get("title", {}).get("rendered", "")))[:40]
    print(f"  #{x['id']:<6} {x['date'][:10]} | {judul:<42} | {x['source_url'][-58:]}")
