#!/usr/bin/env python3
"""Tampilkan isi artikel DAS (untuk penggabungan): judul, sub-judul, dan paragraf."""
import base64, html, importlib.util, json, re, sys, time, urllib.error, urllib.request

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg", f"{WS}/cfg_das.py")
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
CFG = m.CFG
DOM = CFG["domain"]
AUTH = base64.b64encode(f"{CFG['user']}:{CFG['pass']}".encode()).decode()
UA = {"User-Agent": "Mozilla/5.0"}


def rest(path):
    h = {"Authorization": f"Basic {AUTH}", **UA}
    r = urllib.request.Request(f"https://{DOM}{path}", headers=h)
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=180) as x:
                return json.loads(x.read())
        except urllib.error.HTTPError as e:
            return {"err": e.code}
        except Exception:
            time.sleep(4)
    return {}


for pid in sys.argv[1:]:
    p = rest(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=id,slug,title,content,meta,link,date")
    if not isinstance(p, dict) or "content" not in p:
        print(f"#{pid} ❌ {str(p)[:80]}")
        continue
    raw = p["content"]["raw"]
    teks = html.unescape(re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", raw))).strip()
    mm = p.get("meta") or {}
    print(f"\n{'=' * 84}\n#{p['id']} · {p['date'][:10]} · {p['link']}")
    print(f"judul     : {html.unescape(p['title']['raw'])}")
    print(f"yoast     : {mm.get('_yoast_wpseo_title')} | fokus: {mm.get('_yoast_wpseo_focuskw')}")
    print(f"panjang   : {len(teks.split())} kata · h2: {raw.count('<h2')} · h3: {raw.count('<h3')} · "
          f"gambar: {raw.count('<img')} · WA: {'ada' if 'wa.me' in raw else 'tidak'}")
    print("--- sub-judul ---")
    for h in re.findall(r"<h[23][^>]*>(.*?)</h[23]>", raw, re.S):
        print("   " + html.unescape(re.sub(r"<[^>]+>", "", h)).strip()[:90])
    print("--- isi (dipotong) ---")
    print(teks[:1500])
