#!/usr/bin/env python3
"""Coba kembalikan struktur alamat TSLaw ke /%postname%/ lewat XML-RPC, lalu verifikasi.

Kalau metode wp.setOptions tidak tersedia, skrip berhenti tanpa mengubah apa pun.
"""
import re, time, urllib.error, urllib.request
import xmlrpc.client

SITUS = "https://www.tslaw.id"
USER, SANDI = "bambangbot", "EFKm EYGx VQCP Y9go ncPr uM2Y"
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/124.0"}


def status(url):
    try:
        with urllib.request.urlopen(urllib.request.Request(url, headers=UA), 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]}"


p = xmlrpc.client.ServerProxy(f"{SITUS}/xmlrpc.php", allow_none=True)

print("=== 1. baca opsi saat ini ===")
try:
    o = p.wp.getOptions(0, USER, SANDI, ["permalink_structure"])
    print("   hasil:", o)
except Exception as e:
    print("   gagal:", str(e)[:150])

print("\n=== 2. sebelum diubah ===")
for u in (f"{SITUS}/law-firm-surabaya/", f"{SITUS}/law-firm-surabaya.htm"):
    print(f"   {status(u)} · {u}")

print("\n=== 3. coba setel ke /%postname%/ ===")
try:
    r = p.wp.setOptions(0, USER, SANDI, {"permalink_structure": "/%postname%/"})
    print("   balasan:", r)
except Exception as e:
    print("   ❌ metode tidak tersedia / ditolak:", str(e)[:200])
    print("\n   → perubahan harus dilakukan Bos di WordPress: Pengaturan → Permalink → Nama Pos")
    raise SystemExit(0)

time.sleep(4)
print("\n=== 4. sesudah diubah ===")
for u in (f"{SITUS}/law-firm-surabaya/", f"{SITUS}/law-firm-surabaya.htm",
          f"{SITUS}/cara-daftar-cv-pt-online/"):
    print(f"   {status(u)} · {u}")

st, = (status(f"{SITUS}/sitemap_index.xml"),)
print("\n=== 5. sitemap ===")
try:
    idx = urllib.request.urlopen(urllib.request.Request(f"{SITUS}/sitemap_index.xml", headers=UA), timeout=60).read().decode()
    subs = [u for u in re.findall(r"<loc>([^<]+)</loc>", idx) if "post-sitemap" in u]
    if subs:
        t = urllib.request.urlopen(urllib.request.Request(subs[0], headers=UA), timeout=60).read().decode()
        urls = re.findall(r"<loc>([^<]+)</loc>", t)
        print(f"   {len(urls)} entri · berakhiran .htm: {len([u for u in urls if u.endswith('.htm')])}")
        print(f"   contoh: {urls[0]}")
except Exception as e:
    print("   gagal:", str(e)[:60])
