#!/usr/bin/env python3
"""DMark: kembalikan meta artikel uji #2322 ke nilai semula (judul & deskripsi dari halaman cache)."""
import base64, re, time, urllib.request, importlib.util
from xml.sax.saxutils import escape

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg_dmark", f"{WS}/cfg_dmark.py")
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
DOM, USER, PASS = m.CFG.get("domain", "www.dmark.id"), m.CFG["user"], m.CFG["pass"]
AUTH = base64.b64encode(f"{USER}:{PASS}".encode()).decode()
UA = {"User-Agent": "Mozilla/5.0"}
PID = 2322
JUDUL = "7 Strategi Retensi Pelanggan dengan Email Marketing Otomatis"
DESK = ("Tingkatkan loyalitas pelanggan dengan strategi retensi email marketing. Dmark hadir sebagai "
        "solusi untuk membantu bisnis Anda.")


def rpc(method, params=()):
    def val(v):
        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://{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=150) as x:
            return x.read().decode("utf-8", "replace")
    except Exception as e:
        return f"ERR {str(e)[:100]}"


bal = rpc("wp.editPost", [1, USER, PASS, PID, {"custom_fields": [
    {"key": "_yoast_wpseo_title", "value": JUDUL},
    {"key": "_yoast_wpseo_metadesc", "value": DESK}]}])
fault = re.search(r"<name>faultString</name><value><string>(.*?)</string>", bal, re.S)
print("kembalikan meta #2322:", ("GAGAL — " + fault.group(1)[:90]) if fault else "terkirim ✅")
time.sleep(4)

print("\n=== cek halaman artikel (cache) ===")
try:
    h = urllib.request.urlopen(urllib.request.Request(
        f"https://{DOM}/7-strategi-retensi-pelanggan-dengan-email-marketing-otomatis/", headers=UA), timeout=90).read().decode("utf-8", "replace")
    t = re.search(r"<title[^>]*>(.*?)</title>", h, re.S)
    de = re.search(r'<meta name="description" content="([^"]*)"', h, re.I)
    print("   judul:", t.group(1)[:90] if t else "-")
    print("   desc :", de.group(1)[:90] if de else "(tidak ada)")
    print("   ada '(UJI)':", "(UJI)" in h)
except Exception as e:
    print("   gagal:", str(e)[:80])
