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

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
sys.path.insert(0, f"{WS}/drafts")
from tslaw_klaster_konten import ARTIKEL

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)
DOM, AUTH = "www.tslaw.id", base64.b64encode(f'{m.CFG["user"]}:{m.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=200) 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(5)
    return 0, "gagal"


for a in ARTIKEL:
    print(f"\n=== {a['judul'][:70]} ===")
    st, d = req(f"/wp-json/wp/v2/posts?slug={a['slug']}&status=any&_fields=id,link")
    if isinstance(d, list) and d:
        print(f"   sudah ada: #{d[0]['id']} {d[0]['link']} — dilewati")
        continue
    st, d = req("/wp-json/wp/v2/posts", "POST", {
        "title": a["judul"], "slug": a["slug"], "content": a["isi"], "status": "publish",
        "comment_status": "closed", "ping_status": "closed"})
    if not isinstance(d, dict) or "id" not in d:
        print("   GAGAL:", st, str(d)[:200]); continue
    pid, link = d["id"], d["link"]
    kata = len(re.sub(r"<[^>]+>", " ", a["isi"]).split())
    print(f"   ✅ terbit #{pid} → {link} | ±{kata} kata")
    st2, d2 = req(f"/wp-json/wp/v2/posts/{pid}", "POST", {"meta": {
        "_yoast_wpseo_focuskw": a["fokus"], "_yoast_wpseo_title": a["meta_judul"],
        "_yoast_wpseo_metadesc": a["meta_deskripsi"]}})
    meta = (d2 or {}).get("meta") or {}
    print(f"   meta: fokus «{meta.get('_yoast_wpseo_focuskw')}» | judul {len(str(meta.get('_yoast_wpseo_title')))}c | "
          f"deskripsi {len(str(meta.get('_yoast_wpseo_metadesc')))}c")
    time.sleep(2)

print("\n=== daftar artikel terbaru ===")
st, d = req("/wp-json/wp/v2/posts?per_page=6&context=edit&_fields=id,slug,link,status")
for p in d if isinstance(d, list) else []:
    print(f"   #{p['id']} {p['link']}")
