#!/usr/bin/env python3
"""Lihat konteks tepat penyebutan 'klinikdnikrian' pada dua artikel (tanpa @)."""
import base64, importlib.util, json, re, time, urllib.error, urllib.request

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg", f"{WS}/cfg_tsc.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 (1836, 1833, 1939):
    o = rest(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=id,slug,link,content")
    if not isinstance(o, dict):
        print(f"#{pid} gagal")
        continue
    raw = o["content"]["raw"]
    print(f"\n=== #{pid} · {o['link']}")
    print(f"    slug: {o['slug']}")
    for mc in re.finditer(r"klinikdni\w*", raw, re.I):
        awal = max(0, mc.start() - 140)
        potong = re.sub(r"\s+", " ", raw[awal:mc.end() + 90])
        potong = re.sub(r"<[^>]+>", " ", potong).strip()
        print(f"    [{mc.group(0)}] ...{potong[:200]}...")
