#!/usr/bin/env python3
"""Audit tautan internal di 12 draft listikel TSLaw (read-only): mana yang kini 404 karena permalink .htm."""
import base64, json, re, urllib.request, urllib.error

DOM, USER, PASS = "tslaw.id", "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"}
DRAFTS = [3532, 3557, 3653, 3657, 3667, 3671, 3675, 3679, 3685, 3689, 3707, 3717]


def rest(path):
    r = urllib.request.Request(f"https://{DOM}{path}", headers={"Authorization": f"Basic {AUTH}", **UA})
    with urllib.request.urlopen(r, timeout=120) as x:
        return json.loads(x.read())


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


for pid in DRAFTS:
    p = rest(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=id,slug,title,content")
    raw = p["content"]["raw"]
    link = sorted(set(re.findall(r'href="(https://www\.tslaw\.id/[^"]*)"', raw)))
    mati = []
    for u in link:
        if u.rstrip("/") in ("https://www.tslaw.id", "https://www.tslaw.id/layanan",
                             "https://www.tslaw.id/hubungi"):
            continue
        if u.endswith(".htm"):
            continue
        st = cek(u)
        if st != 200:
            mati.append(f"{st} {u}")
    print(f"#{pid} /{p['slug']}/ : {len(link)} tautan internal, {len(mati)} mati")
    for m in mati:
        print(f"    {m}")
