#!/usr/bin/env python3
"""Periksa lebih dalam: struktur permalink TSLaw (lewat XML-RPC), sitemap, dan perilaku URL lama."""
import re, time, urllib.error, urllib.request
import xmlrpc.client

DOM = "www.tslaw.id"
USER, SANDI = "bambangbot", "EFKm EYGx VQCP Y9go ncPr uM2Y"
UA = {"User-Agent": "Mozilla/5.0"}

print("=== 1. pengaturan lewat XML-RPC ===")
try:
    p = xmlrpc.client.ServerProxy(f"https://{DOM}/xmlrpc.php", allow_none=True)
    opsi = p.wp.getOptions(0, USER, SANDI)
    for kunci in ("permalink_structure", "blog_title", "software_version"):
        v = opsi.get(kunci)
        if isinstance(v, dict):
            v = v.get("value")
        print(f"   {kunci}: {v!r}")
except Exception as e:
    print("   gagal:", str(e)[:100])

print("\n=== 2. sitemap: bentuk URL artikel ===")
try:
    idx = urllib.request.urlopen(urllib.request.Request(f"https://{DOM}/sitemap_index.xml", headers=UA), timeout=60).read().decode("utf-8", "replace")
    subs = re.findall(r"<loc>([^<]+)</loc>", idx)
    print("   sub-sitemap:", len(subs))
    for s in subs:
        if "post" in s:
            t = urllib.request.urlopen(urllib.request.Request(s, headers=UA), timeout=60).read().decode("utf-8", "replace")
            urls = re.findall(r"<loc>([^<]+)</loc>", t)
            htm = len([u for u in urls if u.endswith(".htm")])
            print(f"   {s.split('/')[-1]}: {len(urls)} entri · berakhiran .htm: {htm}")
            for u in urls[:3]:
                print(f"      {u}")
except Exception as e:
    print("   gagal:", str(e)[:80])

print("\n=== 3. perilaku URL lama (tanpa .htm) ===")


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


OP = urllib.request.build_opener(TanpaAlih)
for u in ("https://www.tslaw.id/law-firm-surabaya/", "https://www.tslaw.id/law-firm-surabaya",
          "https://www.tslaw.id/law-firm-surabaya.htm", "https://www.tslaw.id/pengacara-surat-wasiat/"):
    try:
        with OP.open(urllib.request.Request(u, headers=UA), timeout=45) as x:
            print(f"   {x.status} · {u}")
    except urllib.error.HTTPError as e:
        print(f"   {e.code} → {e.headers.get('Location','-')[:60]} · {u}")
    except Exception as e:
        print(f"   GAGAL {str(e)[:30]} · {u}")
    time.sleep(0.6)
