#!/usr/bin/env python3
"""1) Daftar artikel publish (untuk pilih tautan internal).
2) Hitung tautan internal .htm vs bersih di semua draft, uji live mana yang 404."""
import base64, json, re, urllib.request, urllib.error, time

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) AppleWebKit/537.36 Chrome/124 Safari/537.36"}


def rest(path):
    h = {"Authorization": f"Basic {AUTH}", **UA}
    r = urllib.request.Request(f"https://{DOM}{path}", headers=h)
    for i in range(3):
        try:
            with urllib.request.urlopen(r, timeout=120) as x:
                return json.loads(x.read())
        except Exception as e:
            print("   (ulang)", str(e)[:60]); time.sleep(5)
    return None


def head(url):
    try:
        with urllib.request.urlopen(urllib.request.Request(url, headers=UA), timeout=60) as x:
            return x.status
    except urllib.error.HTTPError as e:
        return e.code
    except Exception as e:
        return f"ERR {str(e)[:40]}"


print("=== ARTIKEL PUBLISH (id, slug, judul) ===")
pub = []
for pg in range(1, 4):
    r = rest(f"/wp-json/wp/v2/posts?status=publish&per_page=100&page={pg}&_fields=id,slug,title,date")
    if not r:
        break
    pub += r
    if len(r) < 100:
        break
for p in sorted(pub, key=lambda x: x["id"]):
    t = re.sub(r"<[^>]+>", "", p["title"]["rendered"])
    print(f"  #{p['id']} /{p['slug']}/  {t[:80]}")

print(f"\ntotal publish: {len(pub)}")

print("\n=== TAUTAN INTERNAL DI SEMUA DRAFT ===")
drafts = []
for pg in range(1, 3):
    r = rest(f"/wp-json/wp/v2/posts?status=draft&per_page=100&page={pg}&context=edit&_fields=id,slug,content")
    if not r:
        break
    drafts += r
semua_tautan = {}
for d in drafts:
    raw = d.get("content", {}).get("raw", "")
    links = set(re.findall(r'href="(https://www\.tslaw\.id/[^"]*)"', raw))
    htm = [l for l in links if l.endswith(".htm")]
    bersih = [l for l in links if not l.endswith(".htm")]
    print(f"  #{d['id']} /{d['slug']}/  total {len(links)}  .htm {len(htm)}  bersih {len(bersih)}")
    for l in links:
        semua_tautan.setdefault(l, []).append(d["id"])

print(f"\n=== UJI {len(semua_tautan)} TAUTAN UNIK ===")
rusak = []
for u in sorted(semua_tautan):
    st = head(u)
    if st != 200:
        rusak.append((st, u, semua_tautan[u]))
        print(f"  {st}  {u}   (dipakai #{semua_tautan[u]})")
print(f"\ntautan unik: {len(semua_tautan)}; rusak: {len(rusak)}")
htms = [u for u in semua_tautan if u.endswith('.htm')]
print(f"tautan berakhiran .htm: {len(htms)}; semuanya rusak? {all(head(u)!=200 for u in htms)}" if htms else "tidak ada tautan .htm")
