#!/usr/bin/env python3
"""Uji endpoint konten TSC: apakah bisa dibaca dan berapa jumlahnya."""
import base64, importlib.util, json, 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
AUTH = base64.b64encode(f"{CFG['user']}:{CFG['pass']}".encode()).decode()
h = {"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0"}

url = f"https://{CFG['domain']}/wp-json/wp/v2/posts?per_page=3&status=publish&context=edit&_fields=id,link"
r = urllib.request.Request(url, headers=h)
try:
    with urllib.request.urlopen(r, timeout=90) as x:
        d = json.loads(x.read())
        print("HTTP", x.status, "| jumlah:", len(d))
        for p in d:
            print("   ", p["id"], p["link"][:70])
        print("header X-WP-Total:", x.headers.get("X-WP-Total"))
except urllib.error.HTTPError as e:
    print("HTTP", e.code, e.read()[:200])
except Exception as e:
    print("GAGAL", str(e)[:120])

time.sleep(2)
url2 = f"https://{CFG['domain']}/wp-json/wp/v2/posts?per_page=100&page=1&status=publish&context=edit&_fields=id,link,content"
try:
    with urllib.request.urlopen(urllib.request.Request(url2, headers=h), timeout=120) as x:
        d = json.loads(x.read())
        print("halaman 1:", len(d), "artikel | contoh isi panjang:",
              len(d[0]["content"]["raw"]) if d else "-")
except urllib.error.HTTPError as e:
    print("HTTP", e.code, e.read()[:200])
except Exception as e:
    print("GAGAL", str(e)[:120])
