#!/usr/bin/env python3
"""TSC: konteks klaim pada #1905, #1936, #9057 supaya penggantiannya tepat."""
import base64, html, json, re, urllib.request, importlib.util

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

POLA = {
    1905: r"permanen|tanpa risiko|4\.9|70%|BPOM|Halal|MUI|Kemenkes|SpKK|nomor satu",
    1936: r"20%|90%|Rp1|kemenkes|permanen|dijamin",
    9057: r"Kemenkes|BPOM|permanen|dijamin|100%",
}
for pid, pola in POLA.items():
    r = urllib.request.Request(f'https://{m.CFG["domain"]}/wp-json/wp/v2/posts/{pid}?context=edit&_fields=content,title',
                               headers={"Authorization": f"Basic {AUTH}", **UA})
    with urllib.request.urlopen(r, timeout=150) as x:
        d = json.loads(x.read())
    raw = d["content"]["raw"]
    print(f"\n{'='*92}\n### #{pid} {html.unescape(d['title']['rendered'])[:70]}")
    for mm in re.finditer(pola, raw, re.I):
        s = max(0, mm.start() - 220); e = min(len(raw), mm.end() + 160)
        cuplik = re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", raw[s:e]))).strip()
        print(f"   • [{mm.group(0)}] …{cuplik}…")
