#!/usr/bin/env python3
"""Cari artikel TSC bertema kutil / terkait untuk tautan internal + cek kanibalisasi."""
import base64, importlib.util, json, urllib.request, urllib.error, time

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, 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}{path}", data=body, headers=h, method=method)
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=120) as x:
                return x.status, json.loads(x.read())
        except urllib.error.HTTPError as e:
            return e.code, e.read().decode()[:300]
        except Exception as e:
            err = str(e)
            time.sleep(3)
    return 0, err


for q in ("kutil", "tahi lalat", "jamur kuku", "herpes"):
    st, d = rest(f"/wp-json/wp/v2/posts?search={urllib.parse.quote(q)}&per_page=10&status=publish,future,draft&_fields=id,slug,status,date,link,title")
    print(f"\n=== cari: {q} (HTTP {st})")
    if isinstance(d, list):
        for p in d:
            print(f"   #{p['id']:>5} {p['status']:<7} {p.get('date')} {p['slug']}")
    else:
        print("   ", str(d)[:200])
