#!/usr/bin/env python3
"""Diagnosa akses REST DAS: status, izin user, dan jumlah artikel."""
import base64, json, time, urllib.request, urllib.error, importlib.util

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg_das", f"{WS}/cfg_das.py")
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
CFG = m.CFG
DOM = CFG["domain"]
USER, PASS = CFG.get("user"), CFG.get("pass")
AUTH = base64.b64encode(f"{USER}:{PASS}".encode()).decode()
UA = {"User-Agent": "Mozilla/5.0"}
print(f"situs: {DOM} | user: {USER} | password ada: {bool(PASS)}")

def call(p, auth=True):
    h = dict(UA)
    if auth:
        h["Authorization"] = f"Basic {AUTH}"
    r = urllib.request.Request(f"https://{DOM}{p}", headers=h)
    t0 = time.time()
    try:
        with urllib.request.urlopen(r, timeout=90) as x:
            b = x.read()
            return x.status, len(b), dict(x.headers), b[:200]
    except urllib.error.HTTPError as e:
        return e.code, 0, dict(e.headers), e.read()[:200]
    except Exception as e:
        return 0, 0, {}, str(e)[:80].encode()

print("\n=== 1. endpoint dasar ===")
for p, a in (("/wp-json/wp/v2/posts?per_page=1&_fields=id", False),
             ("/wp-json/wp/v2/posts?per_page=1&_fields=id", True),
             ("/wp-json/wp/v2/posts?per_page=1&context=edit&_fields=id", True),
             ("/wp-json/wp/v2/users/me?context=edit", True),
             ("/wp-json/wp/v2/settings", True)):
    st, n, h, b = call(p, a)
    print(f"   {st} | {n:>6} byte | auth={a} | {p[:52]}")
    if st != 200:
        print(f"        {b[:150]}")
    elif "users/me" in p:
        try:
            d = json.loads(b if isinstance(b, bytes) else b)
            print(f"        user: {d.get('name')} | roles: {d.get('roles')}")
        except Exception:
            pass

print("\n=== 2. jumlah artikel (publik, tanpa auth) ===")
st, n, h, b = call("/wp-json/wp/v2/posts?per_page=1&_fields=id", False)
print(f"   status {st} | X-WP-Total: {h.get('X-WP-Total')} | X-WP-TotalPages: {h.get('X-WP-TotalPages')}")

print("\n=== 3. coba tarik 5 artikel dengan context=edit ===")
st, n, h, b = call("/wp-json/wp/v2/posts?per_page=5&context=edit&_fields=id,slug,title", True)
print(f"   status {st} | {n} byte")
print(f"   cuplikan: {b[:300]}")
