#!/usr/bin/env python3
"""TSLaw: periksa & ulangi penautan untuk dua artikel yang gagal (#2831, #2823)."""
import base64, json, re, time, urllib.request, urllib.error, importlib.util

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
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 rest(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()[:300]
        except Exception:
            time.sleep(5)
    return 0, "gagal"


for pid in (2831, 2823):
    st, d = rest(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=slug,content,status")
    if not isinstance(d, dict):
        print(f"#{pid}: gagal baca ({st}) {str(d)[:120]}")
        continue
    raw = d["content"]["raw"] or ""
    ada = "Baca juga:" in raw
    print(f"\n#{pid} /{d['slug']} | status {d.get('status')} | panjang {len(raw)} | sudah ada 'Baca juga:': {ada}")
    if ada:
        print("   sudah tertaut — mungkin hanya gagal verifikasi")
        continue
    print("   (isi belum tertaut)")
