#!/usr/bin/env python3
"""TSLaw: verifikasi pass tautan internal sudah selesai berapa artikel."""
import base64, json, re, time, urllib.request

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=180) as x:
                return json.loads(x.read())
        except Exception:
            time.sleep(3)
    return []


posts, page = [], 1
while True:
    d = rest(f"/wp-json/wp/v2/posts?per_page=100&page={page}&status=publish&context=edit&_fields=id,slug,content")
    if not isinstance(d, list):
        break
    posts += d
    if len(d) < 100:
        break
    page += 1

punya_blok = 0
punya_tautan_keluar = 0
masuk = {}
for p in posts:
    raw = p.get("content", {}).get("raw", "") if isinstance(p.get("content"), dict) else ""
    if "baca juga" in raw.lower():
        punya_blok += 1
    keluar = set(re.findall(r'href="https://www\.tslaw\.id(/[^"]*)"', raw))
    if keluar:
        punya_tautan_keluar += 1
    for k in keluar:
        t = k.strip("/").split("/")[-1]
        masuk[t] = masuk.get(t, 0) + 1

print(f"artikel terbit            : {len(posts)}")
print(f"punya blok 'Baca juga'    : {punya_blok}")
print(f"punya tautan keluar       : {punya_tautan_keluar}")
yatim = [p["slug"] for p in posts if masuk.get(p["slug"], 0) == 0]
print(f"masih yatim (tak ditautkan): {len(yatim)}")
print(f"halaman paling banyak ditautkan: {sorted(masuk.items(), key=lambda x: -x[1])[:6]}")
