#!/usr/bin/env python3
"""Peta bahan untuk klaster artikel turunan #3535 (StudioSoft): kategori, tag, antrean, dan calon tujuan tautan."""
import base64, json, re, urllib.request

DOM = "studiosoft.id"
S = f"https://{DOM}"
AUTH = base64.b64encode(b"bambangbot:q26r RePo BVy6 pwU2 F3z7 ouyl").decode()
H = {"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0"}


def rest(path):
    try:
        return json.loads(urllib.request.urlopen(urllib.request.Request(S + path, headers=H), timeout=120).read())
    except Exception as e:
        return {"err": str(e)[:60]}


print("=== kategori ===")
for c in rest("/wp-json/wp/v2/categories?per_page=60&_fields=id,name,count"):
    if isinstance(c, dict):
        print("   gagal:", c)
        break
    if c["count"]:
        print(f"   #{c['id']:<5} {c['name'][:40]:<42} {c['count']} artikel")

print("\n=== antrean terbit (status future) ===")
f = rest("/wp-json/wp/v2/posts?per_page=30&status=future&orderby=date&order=asc&_fields=id,date,slug")
if isinstance(f, list):
    print(f"   {len(f)} artikel menunggu")
    for x in f[-6:]:
        print(f"   {x['date'][:16]} · {x['slug'][:60]}")
    print("   terakhir:", f[-1]["date"][:16] if f else "-")
else:
    print("   gagal:", f)

print("\n=== artikel bertema rumah sakit/klinik yang hidup (calon tujuan tautan) ===")
kandidat = []
for hal in (1, 2):
    d = rest(f"/wp-json/wp/v2/posts?per_page=100&page={hal}&status=publish&_fields=id,link,slug,title")
    if not isinstance(d, list):
        break
    for x in d:
        s = x["slug"]
        if re.search(r"rumah-sakit|klinik|kesehatan|pasien|dokter|medis|hospital", s):
            kandidat.append((x["id"], s, re.sub("<[^>]+>", "", x["title"]["rendered"])[:70], x["link"]))
print(f"   {len(kandidat)} artikel")
for pid, s, j, link in sorted(kandidat, key=lambda z: z[1]):
    print(f"   #{pid:<5} {s[:58]:<60} {j[:56]}")
