#!/usr/bin/env python3
"""TSLaw: pindai keadaan situs — post, kategori, tag, ketersediaan slug."""
import base64, json, urllib.request, urllib.error

DOM = "tslaw.id"
USER, PASS = "bambangbot", "EFKm EYGx VQCP Y9go ncPr uM2Y"
AUTH = base64.b64encode(f"{USER}:{PASS}".encode()).decode()
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/124 Safari/537.36"}


def rest(path):
    h = {"Authorization": f"Basic {AUTH}", **UA}
    r = urllib.request.Request(f"https://{DOM}{path}", headers=h)
    try:
        with urllib.request.urlopen(r, timeout=120) as x:
            return json.loads(x.read()), dict(x.headers)
    except urllib.error.HTTPError as e:
        return {"error": e.code, "body": e.read().decode()[:200]}, {}


posts, hdr = rest("/wp-json/wp/v2/posts?per_page=100&orderby=date&order=desc&status=publish,future,draft&_fields=id,title,slug,status,date,categories,tags")
if isinstance(posts, dict):
    print("GAGAL:", posts)
    raise SystemExit(1)
print(f"Total post: {len(posts)} (header X-WP-Total: {hdr.get('X-WP-Total')})")
for p in sorted(posts, key=lambda x: x["id"]):
    print(f"  #{p['id']:<5} {p['status']:<8} {p['date'][:10]} {p['slug'][:52]:<54} {p['title']['rendered'][:70]}")
    print(f"          kat={p['categories']} tag={p['tags']}")

cats, _ = rest("/wp-json/wp/v2/categories?per_page=100&_fields=id,name,slug,count")
print("\nKATEGORI:")
for c in cats:
    print(f"  {c['id']:<5} {c['slug'][:30]:<32} {c['name']} ({c['count']})")

tags, hdr2 = rest("/wp-json/wp/v2/tags?per_page=100&orderby=count&order=desc&_fields=id,name,slug,count")
print(f"\nTAG (total {hdr2.get('X-WP-Total')}):")
for t in tags:
    print(f"  {t['id']:<5} {t['slug'][:32]:<34} {t['name']} ({t['count']})")

for slug in ["pengacara-sengketa-tanah-surabaya", "pengacara-sengketa-tanah-dan-sertifikat-surabaya"]:
    q, _ = rest(f"/wp-json/wp/v2/posts?slug={slug}&status=any&_fields=id,slug,status,link")
    print(f"\nslug '{slug}': {q if q else 'BELUM ADA (aman)'}")
