#!/usr/bin/env python3
"""Periksa struktur permalink TSLaw dan apakah URL .htm berlaku untuk semua artikel."""
import base64, json, time, urllib.error, urllib.request

DOM = "www.tslaw.id"
AUTH = base64.b64encode(b"bambangbot:EFKm EYGx VQCP Y9go ncPr uM2Y").decode()
h = {"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0"}
UA = {"User-Agent": "Mozilla/5.0"}


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


print("=== struktur permalink (pengaturan situs) ===")
r = urllib.request.Request(f"https://{DOM}/wp-json/wp/v2/settings", headers=h)
try:
    d = json.loads(urllib.request.urlopen(r, timeout=90).read())
    print("   permalink_structure:", repr(d.get("permalink_structure")))
except urllib.error.HTTPError as e:
    print("   gagal baca pengaturan:", e.code, e.read()[:120])

print("\n=== 5 artikel TSLaw: URL asli vs +.htm ===")
r2 = urllib.request.Request(f"https://{DOM}/wp-json/wp/v2/posts?per_page=5&status=publish&orderby=date&order=desc&_fields=id,slug,link", headers=h)
try:
    posts = json.loads(urllib.request.urlopen(r2, timeout=120).read())
except Exception as e:
    posts = []
    print("   gagal ambil daftar:", str(e)[:60])

for x in posts:
    slug = x["slug"]
    bersih = cek(f"https://{DOM}/{slug}/")
    htm = cek(f"https://{DOM}/{slug}.htm")
    print(f"   #{x['id']:<5} /{slug[:46]:<48} → /slug/ {bersih} | /slug.htm {htm}")
    print(f"        link dari API: {x['link']}")
    time.sleep(0.8)

print("\n=== beranda dan halaman lain ===")
for u in ("https://www.tslaw.id/", "https://www.tslaw.id/sitemap_index.xml",
          "https://www.tslaw.id/cara-memilih-law-firm-surabaya-untuk-perusahaan/"):
    print(f"   {cek(u)} · {u[:70]}")
