#!/usr/bin/env python3
"""TSLaw: cek pengguna WordPress, sebaran penulis artikel, lalu siapkan perubahan nama jadi 'Assistant'."""
import base64, json, re, sys, time, urllib.request, urllib.error, importlib.util
from collections import Counter

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, timeout=150):
    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=timeout) 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(4)
    return 0, "gagal"


print("=== pengguna yang bisa dibaca ===")
st, users = rest("/wp-json/wp/v2/users?per_page=20&context=edit")
if isinstance(users, list):
    for u in users:
        print(f"   id {u['id']:<3} name=«{u.get('name')}» slug={u.get('slug')} "
              f"first={u.get('first_name')!r} last={u.get('last_name')!r} nick={u.get('nickname')!r}")
else:
    print("   gagal:", st, str(users)[:200])

print("\n=== pengguna saat ini (yang dipakai kredensial) ===")
st, me = rest("/wp-json/wp/v2/users/me?context=edit")
print(f"   status {st} | {json.dumps(me)[:300] if isinstance(me, dict) else str(me)[:200]}")

print("\n=== sebaran penulis artikel ===")
posts, page, c = [], 1, Counter()
while True:
    st, d = rest(f"/wp-json/wp/v2/posts?per_page=100&page={page}&status=publish&context=edit&_fields=id,author")
    if not isinstance(d, list):
        break
    posts += d
    for p in d:
        c[p["author"]] += 1
    if len(d) < 100:
        break
    page += 1
print(f"   {dict(c)}  (total {len(posts)} artikel)")
