#!/usr/bin/env python3
"""TSLaw: periksa format artikel yang sudah ada (struktur, CTA, schema, kategori) sebagai acuan."""
import base64, html, json, re, time, urllib.request, urllib.error

DOM = "tslaw.id"
AUTH = base64.b64encode(b"bambangbot:EFKm EYGx VQCP Y9go ncPr uM2Y").decode()
UA = {"User-Agent": "Mozilla/5.0"}


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


print("=== kategori & tag ===")
for tipe in ("categories", "tags"):
    d = rest(f"/wp-json/wp/v2/{tipe}?per_page=100&_fields=id,name,count")
    if isinstance(d, list):
        print(f"  {tipe}:")
        for c in sorted(d, key=lambda x: -x["count"])[:10]:
            print(f"     #{c['id']:>4} {html.unescape(c['name'])[:40]:<42} {c['count']}")

print("\n=== 6 artikel terakhir ===")
d = rest("/wp-json/wp/v2/posts?per_page=6&status=publish,future&_fields=id,title,link,date,categories,featured_media,status")
for p in d if isinstance(d, list) else []:
    print(f"  #{p['id']:>5} [{p['status']:<7}] {p['date'][:10]} {p['link'].replace('https://www.tslaw.id','')[:52]}")
    print(f"        {html.unescape(p['title']['rendered'])[:78]} | kat {p['categories']} | gambar {p['featured_media']}")

pid = d[0]["id"] if isinstance(d, list) and d else None
if pid:
    p = rest(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=content,title,meta")
    raw = p.get("content", {}).get("raw", "")
    print(f"\n=== struktur artikel #{pid} ({len(raw)} char) ===")
    print("  blok:", {k: raw.count("<!-- wp:" + k) for k in
                      ("paragraph", "heading", "list", "image", "buttons", "html", "group")})
    print("  H2:", [html.unescape(re.sub(r"<[^>]+>", "", x))[:52] for x in re.findall(r"<h2[^>]*>(.*?)</h2>", raw, re.S)][:10])
    print("  CTA/wa.me:", re.findall(r"https?://wa\.me/\d+", raw)[:3] or "TIDAK ADA")
    print("  schema:", "FAQPage" if "FAQPage" in raw else ("ada ld+json" if "ld+json" in raw else "tidak ada"))
    print("  link internal:", sorted(set(re.findall(r'href="https://www\.tslaw\.id([^"]*)"', raw)))[:8])
    print("  catatan meta:", {k: (v[:60] if isinstance(v, str) else v) for k, v in list((p.get("meta") or {}).items())[:6]})
    print("\n  60 karakter pertama:", raw[:200].replace("\n", " "))

print("\n=== halaman tetap (untuk link ke beranda & lainnya) ===")
pg = rest("/wp-json/wp/v2/pages?per_page=100&_fields=id,link,title")
for x in pg if isinstance(pg, list) else []:
    print(f"  #{x['id']:>5} {x['link'].replace('https://www.tslaw.id','')[:40]:<42} {html.unescape(x['title']['rendered'])[:30]}")
