#!/usr/bin/env python3
"""TSLaw: (1) bersihkan /hubungi/ dari lorem ipsum + nomor palsu lewat REST,
(2) set meta Yoast beranda lewat XML-RPC dengan escaping XML yang benar."""
import base64, json, re, sys, time, 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()
UA = {"User-Agent": "Mozilla/5.0"}


def rest(path, method="GET", data=None):
    h = {"Authorization": f"Basic {AUTH}", **UA}
    body = None
    if data is not None:
        body = json.dumps(data).encode(); h["Content-Type"] = "application/json"
    r = urllib.request.Request(f"https://{DOM}{path}", data=body, headers=h, method=method)
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=180) as x:
                return x.status, json.loads(x.read())
        except urllib.error.HTTPError as e:
            return e.code, e.read().decode()[:250]
        except Exception:
            time.sleep(4)
    return 0, "gagal"


def rpc(method, params=()):
    """XML-RPC dengan escaping yang benar (pelajaran dari insiden)."""
    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")
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=150) 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:
            time.sleep(4)
    return 0, "gagal"


print("=== 1. /hubungi/: bersihkan teks template & nomor palsu ===")
st, d = rest("/wp-json/wp/v2/pages/10?context=edit&_fields=content")
raw = d.get("content", {}).get("raw", "") if isinstance(d, dict) else ""
open("/home/mantapman/.hermes/profiles/atun/workspace/tslaw_pemulihan/salinan/10_hubungi_sebelum_edit.txt", "w").write(raw)
print(f"   konten sekarang: {len(raw)} karakter (salinan disimpan)")

GANTI = [
    ('"text":"Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec velit neque."',
     '"text":"Sampaikan persoalan hukum Anda, kami akan menilai langkah awal yang paling tepat."'),
    ('"text":"+1 1184 4457 44\\u003cbr\\u003e+1 4487 4477 11"',
     '"text":"+62 819 0922 2026"'),
]
baru = raw
for lama, ganti in GANTI:
    n = baru.count(lama)
    print(f"   {n}x → {lama[:70]}")
    baru = baru.replace(lama, ganti)

if baru != raw:
    st, res = rest("/wp-json/wp/v2/pages/10", "POST", {"content": baru})
    print(f"   simpan: HTTP {st}")
    st, cek = rest("/wp-json/wp/v2/pages/10?context=edit&_fields=content")
    now = cek.get("content", {}).get("raw", "") if isinstance(cek, dict) else ""
    print(f"   verifikasi: {len(now)} karakter | lorem tersisa: {now.count('Vestibulum')} | "
          f"nomor palsu tersisa: {now.count('+1 1184')} | nomor asli: {now.count('+62 819')}")
else:
    print("   (tidak ada yang perlu diubah)")

print("\n=== 2. meta Yoast beranda (XML-RPC dengan escaping) ===")
CF = [{"key": "_yoast_wpseo_title", "value": "Law Firm Surabaya | Tito Suprianto Law Firm"},
      {"key": "_yoast_wpseo_metadesc", "value": "Law firm Surabaya untuk sengketa tanah, kontrak bisnis, merek dagang, dan legalitas usaha. Konsultasi gratis bersama advokat Tito Suprianto Law Firm."},
      {"key": "_yoast_wpseo_focuskw", "value": "law firm surabaya"}]
st, isi = rpc("wp.editPost", [1, USER, PASS, 833, {"custom_fields": CF}])
print(f"   HTTP {st} | tersimpan: {'✅' if '<boolean>1</boolean>' in isi else '❌ ' + re.sub(chr(10), ' ', isi)[:150]}")

print("\n=== 3. verifikasi lewat Yoast ===")
for u in ("https://www.tslaw.id/", "https://www.tslaw.id/hubungi/"):
    try:
        r = urllib.request.urlopen(urllib.request.Request(
            f"https://{DOM}/wp-json/yoast/v1/get_head?url={u}", headers=UA), timeout=90)
        j = json.loads(r.read()).get("json", {})
        print(f"   {u.replace('https://www.tslaw.id', ''):<12} judul: {str(j.get('title'))[:56]:<58} meta: {len(j.get('description') or '')} char")
    except Exception as e:
        print(f"   {u}: gagal {str(e)[:60]}")
