#!/usr/bin/env python3
"""TSLaw: ubah nama penulis jadi 'Assistant' dan satukan seluruh artikel ke penulis itu."""
import base64, json, re, sys, 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"}
PENULIS = 2


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=180) 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("=== sebelum ===")
st, u = rest("/wp-json/wp/v2/users/2?context=edit")
print(f"   {st} | name=«{(u or {}).get('name')}» first={(u or {}).get('first_name')!r} "
      f"last={(u or {}).get('last_name')!r} nick={(u or {}).get('nickname')!r}")

print("\n=== ubah nama jadi 'Assistant' ===")
st, d = rest("/wp-json/wp/v2/users/2", "POST", {"name": "Assistant", "first_name": "", "last_name": "",
                                                "nickname": "Assistant"})
print(f"   status {st} | {json.dumps(d)[:250] if isinstance(d, dict) else str(d)[:250]}")
time.sleep(2)
st, u2 = rest("/wp-json/wp/v2/users/2?context=edit")
print(f"   sesudah: name=«{(u2 or {}).get('name')}» first={(u2 or {}).get('first_name')!r} "
      f"last={(u2 or {}).get('last_name')!r} nick={(u2 or {}).get('nickname')!r}")

print("\n=== satukan artikel ke penulis 'Assistant' ===")
posts, page = [], 1
while True:
    st, d = rest(f"/wp-json/wp/v2/posts?per_page=100&page={page}&status=publish&context=edit&_fields=id,slug,author")
    if not isinstance(d, list):
        break
    posts += d
    if len(d) < 100:
        break
    page += 1
lain = [p for p in posts if p["author"] != PENULIS]
print(f"   artikel dengan penulis lain: {len(lain)}")
for p in lain:
    st2, d2 = rest(f"/wp-json/wp/v2/posts/{p['id']}", "POST", {"author": PENULIS})
    st3, cek = rest(f"/wp-json/wp/v2/posts/{p['id']}?context=edit&_fields=author")
    ok = isinstance(cek, dict) and cek.get("author") == PENULIS
    print(f"      #{p['id']} /{p['slug'][:44]:<46} {'✅' if ok else '⚠️ gagal'}")
    time.sleep(1)

print("\n=== verifikasi akhir ===")
from collections import Counter
page, c = 1, Counter()
posts2 = []
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
    posts2 += d
    for p in d:
        c[p["author"]] += 1
    if len(d) < 100:
        break
    page += 1
print(f"   sebaran penulis sekarang: {dict(c)} (total {len(posts2)})")
