#!/usr/bin/env python3
"""TSLaw: terbitkan artikel pilar 'law firm surabaya' + setel meta Yoast, lalu verifikasi."""
import base64, html, json, sys, time, urllib.request, urllib.error, importlib.util

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
sys.path.insert(0, f"{WS}/drafts")
from tslaw_pilar_konten import JUDUL, SLUG, FOKUS, META_JUDUL, META_DESKRIPSI, ISI

spec = importlib.util.spec_from_file_location("cfg_tslaw", f"{WS}/cfg_tslaw.py")
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
CFG = m.CFG
DOM, AUTH = "www.tslaw.id", base64.b64encode(f'{CFG["user"]}:{CFG["pass"]}'.encode()).decode()
UA = {"User-Agent": "Mozilla/5.0"}


def req(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=180) as x:
                return x.status, json.loads(x.read())
        except urllib.error.HTTPError as e:
            return e.code, e.read().decode()[:300]
        except Exception:
            time.sleep(5)
    return 0, "gagal"


print("=== cek dulu apakah slug sudah terpakai ===")
st, d = req(f"/wp-json/wp/v2/posts?slug={SLUG}&status=any&_fields=id,link,status")
print(f"   status {st} | hasil: {d if isinstance(d, list) else str(d)[:120]}")
if isinstance(d, list) and d:
    print("   sudah ada, tidak diterbitkan ulang:", d[0])
    sys.exit(0)

print("\n=== menerbitkan artikel pilar ===")
st, d = req("/wp-json/wp/v2/posts", "POST", {
    "title": JUDUL, "slug": SLUG, "content": ISI, "status": "publish",
    "comment_status": "closed", "ping_status": "closed",
})
if not isinstance(d, dict) or "id" not in d:
    print("   GAGAL:", st, str(d)[:300]); sys.exit(1)
PID, LINK = d["id"], d["link"]
print(f"   ✅ terbit: #{PID} → {LINK}")
print(f"      panjang isi: {len(ISI)} karakter | ±{len(ISI.split())} kata")

print("\n=== setel meta Yoast (lewat REST) ===")
st, d2 = req(f"/wp-json/wp/v2/posts/{PID}", "POST", {"meta": {
    "_yoast_wpseo_focuskw": FOKUS, "_yoast_wpseo_title": META_JUDUL, "_yoast_wpseo_metadesc": META_DESKRIPSI}})
print(f"   status {st} | meta tersimpan: {(d2 or {}).get('meta') if isinstance(d2, dict) else str(d2)[:200]}")

print("\n=== verifikasi dari API ===")
st, d3 = req(f"/wp-json/wp/v2/posts/{PID}?context=edit&_fields=id,link,slug,title,meta,status")
if isinstance(d3, dict):
    print(f"   #{d3['id']} | {d3['status']} | {d3['link']}")
    print(f"   judul: {html.unescape(re.sub('<[^>]+>','',d3['title']['raw']))[:80]}")
    meta = d3.get("meta") or {}
    for k in ("_yoast_wpseo_focuskw", "_yoast_wpseo_title", "_yoast_wpseo_metadesc"):
        print(f"   {k:<26} {str(meta.get(k))[:90]}")
