#!/usr/bin/env python3
"""DMark: daftar plugin aktif/nonaktif lewat REST (kalau izinnya cukup)."""
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_dmark", f"{WS}/cfg_dmark.py")
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
DOM = m.CFG.get("domain", "www.dmark.id")
AUTH = base64.b64encode(f'{m.CFG["user"]}:{m.CFG["pass"]}'.encode()).decode()
UA = {"User-Agent": "Mozilla/5.0"}


def rest(p):
    h = {"Authorization": f"Basic {AUTH}", **UA}
    r = urllib.request.Request(f"https://{DOM}{p}", headers=h)
    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()[:200]
        except Exception:
            time.sleep(3)
    return 0, "gagal"


st, d = rest("/wp-json/wp/v2/plugins")
print(f"status {st}")
if isinstance(d, list):
    for p in d:
        print(f"   {p.get('status'):<10} {p.get('plugin'):<58} {p.get('name')}")
else:
    print("   balasan:", str(d)[:200])

print("\n=== siapa pengguna yang dipakai kredensial ini ===")
st2, me = rest("/wp-json/wp/v2/users/me?context=edit")
if isinstance(me, dict):
    print(f"   id {me.get('id')} | {me.get('name')} | peran: {me.get('roles')} | kemampuan kunci: "
          f"{[k for k in (me.get('capabilities') or {}) if k in ('activate_plugins','edit_plugins','manage_options','edit_pages','edit_posts')]}")
else:
    print("   ", st2, str(me)[:200])

print("\n=== tipe konten terdaftar (menunjukkan plugin pembangun yang aktif) ===")
st3, tipe = rest("/wp-json/wp/v2/types")
if isinstance(tipe, dict):
    print("   ", sorted(tipe.keys()))
