#!/usr/bin/env python3
"""Uji bentuk alamat untuk beberapa post tslaw.id: bersih /, .htm, dan ?p=ID."""
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) 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)
    with urllib.request.urlopen(r, timeout=120) as x:
        return json.loads(x.read())


def head(url, follow=True):
    req = urllib.request.Request(url, headers=UA)
    opener = urllib.request.build_opener() if follow else urllib.request.build_opener(NoRedirect())
    try:
        with opener.open(req, timeout=60) as x:
            return x.status, x.geturl()
    except urllib.error.HTTPError as e:
        return e.code, url
    except Exception as e:
        return f"ERR {str(e)[:50]}", url


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *a, **k):
        return None


# ambil semua post tayang terbaru
posts = []
for s in ["publish", "future"]:
    for pg in range(1, 6):
        try:
            r = rest(f"/wp-json/wp/v2/posts?status={s}&per_page=100&page={pg}&context=edit&_fields=id,slug,link,status,date")
        except Exception as e:
            break
        if not r:
            break
        posts += r
        if len(r) < 100:
            break
print(f"post ditarik: {len(posts)}")

contoh = [p for p in posts if p["id"] in (2928, 3057, 3698, 3679, 3722)]
for p in posts[:0]:
    pass
# tambahkan beberapa draft terbaru juga
drafts = rest("/wp-json/wp/v2/posts?status=draft&per_page=5&context=edit&_fields=id,slug,link,status,date")
contoh = posts[:6] + drafts

print("\n=== UJI BENTUK ALAMAT ===")
for p in contoh:
    slug = p["slug"]
    forms = {
        "link API": p["link"],
        "slug/": f"https://www.tslaw.id/{slug}/",
        "slug.htm": f"https://www.tslaw.id/{slug}.htm",
        "?p=ID": f"https://www.tslaw.id/?p={p['id']}",
    }
    print(f"\n  #{p['id']} [{p['status']}] {slug}")
    for nama, u in forms.items():
        st, fin = head(u)
        tanda = ""
        if fin != u:
            tanda = f"  -> {fin}"
        print(f"    {nama:<9} {st}{tanda}")

# uji sitemap
print("\n=== SITEMAP ===")
for u in ["https://www.tslaw.id/sitemap_index.xml", "https://www.tslaw.id/post-sitemap.xml"]:
    st, fin = head(u)
    print(f"  {st}  {u}")
try:
    d = urllib.request.urlopen(urllib.request.Request("https://www.tslaw.id/post-sitemap.xml", headers=UA), timeout=60).read().decode()
    lacak = __import__("re").findall(r"<loc>([^<]+)</loc>", d)
    print(f"  entri sitemap: {len(lacak)}; contoh teratas:")
    for l in lacak[:8]:
        print("     ", l)
except Exception as e:
    print("  gagal baca sitemap:", e)
