#!/usr/bin/env python3
"""TSLaw: baca setelan Yoast untuk beranda (wpseo_titles) + nilai meta halaman beranda.
Hanya BACA dulu — sebelum mengubah apa pun."""
import base64, json, re, urllib.request, urllib.error
from xml.sax.saxutils import escape

DOM = "tslaw.id"
USER, PASS = "bambangbot", "EFKm EYGx VQCP Y9go ncPr uM2Y"
AUTH = base64.b64encode(f"{USER}:{PASS}".encode()).decode()


def rpc(method, params=()):
    def val(v):
        if isinstance(v, bool):
            return f"<value><boolean>{1 if v else 0}</boolean></value>"
        if isinstance(v, int):
            return f"<value><int>{v}</int></value>"
        if isinstance(v, list):
            return "<value><array><data>" + "".join(val(x) for x in v) + "</data></array></value>"
        if isinstance(v, dict):
            return "<value><struct>" + "".join(f"<member><name>{escape(str(k))}</name>{val(x)}</member>"
                                               for k, x in v.items()) + "</struct></value>"
        return f"<value><string>{escape(str(v))}</string></value>"
    body = ("<?xml version=\"1.0\"?><methodCall><methodName>" + method + "</methodName><params>" +
            "".join(f"<param>{val(p)}</param>" for p in params) + "</params></methodCall>").encode()
    r = urllib.request.Request(f"https://www.{DOM}/xmlrpc.php", data=body,
                               headers={"Content-Type": "text/xml", "User-Agent": "Mozilla/5.0",
                                        "Authorization": f"Basic {AUTH}"}, method="POST")
    try:
        with urllib.request.urlopen(r, timeout=180) 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. bisakah wpseo_titles dibaca lewat wp.getOptions? ===")
st, isi = rpc("wp.getOptions", [1, USER, PASS, ["wpseo_titles"]])
print(f"   HTTP {st} | panjang respons: {len(isi)}")
status = re.search(r"<name>wpseo_titles</name><value><struct>.*?<name>option_status</name><value><string>([^<]*)", isi, re.S)
print("   status opsi:", status.group(1) if status else "(tidak terbaca)")

# ambil nilai-nilai yang berkaitan dengan beranda
for kunci in ("title-home-wpseo", "metadesc-home-wpseo", "title-page", "metadesc-page",
              "title-post", "metadesc-post", "title-author-wpseo", "noindex-author-wpseo",
              "noindex-search", "noindex-subpages-wpseo"):
    m = re.search(rf"<name>{re.escape(kunci)}</name><value><(?:string|array|struct|int|boolean)>([^<]*(?:<(?!/(?:value|array|struct|data)>)[^<]*)*)", isi)
    if m:
        nilai = re.sub(r"<[^>]+>", " ", m.group(1))
        nilai = re.sub(r"\s+", " ", nilai).strip()
        print(f"   {kunci:<26} = {nilai[:80]}")
    else:
        print(f"   {kunci:<26} = (tidak ada di respons)")

print("\n=== 2. meta Yoast yang terpasang di halaman beranda (#833) ===")
st, isi = rpc("wp.getPost", [1, USER, PASS, 833])
for kunci in ("_yoast_wpseo_title", "_yoast_wpseo_metadesc", "_yoast_wpseo_focuskw"):
    for m in re.finditer(r"<member><name>key</name><value><string>" + re.escape(kunci) +
                         r"</string></value></member>\s*<member><name>value</name><value><string>(.*?)</string>", isi, re.S):
        print(f"   {kunci:<24} {m.group(1)[:90]}")

print("\n=== 3. apa yang tampil di halaman live sekarang ===")
h = urllib.request.urlopen(urllib.request.Request("https://www.tslaw.id/?cek=1",
                                                  headers={"User-Agent": "Mozilla/5.0"}), timeout=90).read().decode("utf-8", "replace")
t = re.search(r"<title>(.*?)</title>", h, re.S)
d = re.search(r'<meta name="description" content="([^"]*)"', h)
print(f"   judul: {t.group(1) if t else '-'}")
print(f"   meta : {d.group(1)[:120] if d else '-'}")
