#!/usr/bin/env python3
"""Pra-tulis: cari artikel lama bertema schema/structured data, daftar kategori, uji tautan internal."""
import base64, json, re, sys, time, urllib.error, urllib.request

DOM = "studiosoft.id"
AUTH = base64.b64encode(b"bambangbot:q26r RePo BVy6 pwU2 F3z7 ouyl").decode()
UA = {"User-Agent": "Mozilla/5.0"}


def rest(p):
    h = {"Authorization": f"Basic {AUTH}", **UA}
    for i in range(3):
        try:
            r = urllib.request.Request(f"https://{DOM}{p}", headers=h)
            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()[:200]
        except Exception:
            time.sleep(4)
    return 0, "gagal"


print("== artikel yang menyebut schema / structured data di judul ==")
for kw in ("schema", "structured+data", "markup", "local+business", "microdata"):
    st, d = rest(f"/wp-json/wp/v2/posts?search={kw}&per_page=20&status=publish,future,draft&_fields=id,title,slug,status")
    if isinstance(d, list):
        hits = [f"#{p['id']} [{p['status']}] {p['title']['rendered'][:70]}" for p in d
                if re.search(r"schema|structured|markup|microdata", p["title"]["rendered"], re.I)]
        print(f"  '{kw}': {len(d)} hasil, judul cocok: {len(hits)}")
        for h in hits[:8]:
            print("     ", h)
    else:
        print(f"  '{kw}': HTTP {st} {str(d)[:100]}")

print("\n== kategori ==")
st, cats = rest("/wp-json/wp/v2/categories?per_page=100&_fields=id,name,count")
if isinstance(cats, list):
    for c in cats:
        print(f"  {c['id']:5d} {c['name']} ({c['count']})")
else:
    print("  gagal", st, cats)
