#!/usr/bin/env python3
"""TSC: periksa item menu — item menu menyimpan jenis objek (page/post) walau kontennya sudah dihapus."""
import base64, html, json, re, time, urllib.request, urllib.error, importlib.util

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg_tsc", f"{WS}/cfg_tsc.py")
mod = importlib.util.module_from_spec(spec); spec.loader.exec_module(mod)
CFG = mod.CFG
DOM = CFG["domain"]
AUTH = base64.b64encode(f'{CFG["user"]}:{CFG["pass"]}'.encode()).decode()
UA = {"User-Agent": "Mozilla/5.0"}


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


print("=== lokasi menu (menu locations) ===")
st, lok = rest("/wp-json/wp/v2/menu-locations")
if isinstance(lok, list):
    for l in lok:
        print(f"   {l.get('name')}: {l.get('description', '')[:60]} | menu id {l.get('menu')} | {l.get('locations')}")
else:
    print("   ", st, str(lok)[:100])

print("\n=== item menu ===")
st, items = rest("/wp-json/wp/v2/menu-items?per_page=100&_fields=id,title,url,type,object,object_id,parent,menus")
if isinstance(items, list):
    for it in items:
        judul = html.unescape(str(it.get("title", {}).get("rendered", "")))[:34]
        print(f"   {judul:<36} {it.get('url', '')[:64]:<66} type={it.get('type')} object={it.get('object')} id={it.get('object_id')}")
else:
    print("   ", st, str(items)[:120])

print("\n=== cari URL mati di item menu ===")
CARI = ["jadwal", "profil", "dermatologi-anak", "tahi-lalat", "klinik-dermatologi-terpercaya"]
ketemu = False
for it in (items if isinstance(items, list) else []):
    for c in CARI:
        if c in str(it.get("url", "")):
            print(f"   DITEMUKAN: {it.get('url')} → type={it.get('type')} object={it.get('object')} id={it.get('object_id')}")
            ketemu = True
if not ketemu:
    print("   tidak ada item menu yang menunjuk URL mati itu")

print("\n=== semua menu yang ada ===")
st, menus = rest("/wp-json/wp/v2/menus?per_page=50")
if isinstance(menus, list):
    for mn in menus:
        print(f"   #{mn.get('id')} {mn.get('name')} ({mn.get('locations')})")
