#!/usr/bin/env python3
"""EveryBe: tulis meta Yoast artikel #2663 (tone up) lewat REST — jalur XML-RPC tidak berpengaruh."""
import base64, json, sys, time, urllib.request, urllib.error, importlib.util

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg_everybe", f"{WS}/cfg_everybe.py")
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
CFG = m.CFG
DOM = CFG.get("domain", "www.everybeofficial.com")
AUTH = base64.b64encode(f'{CFG["user"]}:{CFG["pass"]}'.encode()).decode()
UA = {"User-Agent": "Mozilla/5.0"}
PID = 2663
META = {
    "_yoast_wpseo_title": "Tone Up Body Lotion EveryBe — Kulit Lebih Cerah & Merata",
    "_yoast_wpseo_metadesc": ("Tone Up Body Lotion EveryBe membantu mencerahkan dan meratakan warna kulit "
                              "bila dipakai rutin. Lihat manfaat, cara pakai, dan keterangannya di sini."),
    "_yoast_wpseo_focuskw": "tone up body lotion everybe",
}


def rest(p, 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}{p}", data=body, headers=h, method=method)
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=150) 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(3)
    return 0, "gagal"


print("=== sebelum ===")
st, d = rest(f"/wp-json/wp/v2/posts/{PID}?context=edit&_fields=meta")
before = (d or {}).get("meta", {}) if isinstance(d, dict) else {}
print(f"   judul: {str(before.get('_yoast_wpseo_title'))[:90]}")
print(f"   desc : {str(before.get('_yoast_wpseo_metadesc'))[:90]}")

print("\n=== menulis lewat REST ===")
st2, d2 = rest(f"/wp-json/wp/v2/posts/{PID}", "POST", {"meta": META})
print(f"   status {st2}")
after = (d2 or {}).get("meta", {}) if isinstance(d2, dict) else {}
print(f"   judul terpasang: {str(after.get('_yoast_wpseo_title'))[:90]}")
print(f"   desc terpasang : {str(after.get('_yoast_wpseo_metadesc'))[:90]}")

print("\n=== verifikasi di halaman live ===")
time.sleep(4)
import re
for q in ("", "?nocache=1"):
    try:
        h = urllib.request.urlopen(urllib.request.Request(
            f"https://{DOM}/tone-up-body-lotion-rahasia-kulit-cerah-halus-dan-merata-setiap-hari/{q}", 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(f"   q='{q or '(kosong)'}': {t.group(1)[:80] if t else '-'}")
        print(f"      desc: {de.group(1)[:100] if de else '-'}")
    except Exception as e:
        print(f"   q='{q}' gagal: {str(e)[:70]}")
