#!/usr/bin/env python3
"""TSLaw: uji jalur XML-RPC untuk menulis meta Yoast (karena REST tidak mengeksposnya)."""
import base64, json, re, 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", "Content-Type": "text/xml"}


def rpc(method, params):
    body = f"""<?xml version="1.0"?>
<methodCall><methodName>{method}</methodName><params>
{' '.join(params)}
</params></methodCall>""".encode()
    r = urllib.request.Request(f"https://www.{DOM}/xmlrpc.php", data=body,
                               headers={**UA, "Authorization": f"Basic {AUTH}"}, method="POST")
    try:
        with urllib.request.urlopen(r, timeout=90) as x:
            return x.status, x.read().decode("utf-8", "replace")
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode("utf-8", "replace")[:300]
    except Exception as e:
        return 0, str(e)[:150]


print("=== 1. apakah XML-RPC hidup? ===")
st, isi = rpc("wp.getProfile", ["1", USER, PASS])
print(f"   HTTP {st}")
if st == 200 and "<name>" in isi:
    nama = re.search(r"<name>([^<]*)</name>", isi)
    roles = re.findall(r"<value><string>([^<]*)</string></value>", isi)[:6]
    print("   berhasil login XML-RPC. user:", nama.group(1) if nama else "?", "| string pertama:", roles)
    print("   cuplikan:", isi[:200].replace("\n", " "))
else:
    print("   gagal / dimatikan:", isi[:300].replace("\n", " "))

print("\n=== 2. baca meta halaman 834 lewat XML-RPC ===")
st, isi = rpc("wp.getPost", ["1", USER, PASS, "834", "custom_fields"])
if st == 200:
    kunci = re.findall(r"<name>([^<]+)</name>", isi)
    print("   jumlah custom field terbaca:", len(kunci))
    print("   contoh:", kunci[:10])
else:
    print("   gagal:", isi[:200].replace("\n", " "))

print("\n=== 3. REST: apakah kunci Yoast muncul tanpa _fields? ===")
r = urllib.request.Request(f"https://{DOM}/wp-json/wp/v2/pages/834?context=edit",
                           headers={"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(r, timeout=90) as x:
    d = json.loads(x.read())
print("   meta keys:", sorted((d.get("meta") or {}).keys())[:10])
print("   ada yoast_head_json:", "yoast_head_json" in d)
