#!/usr/bin/env python3
"""TSC: pakai kredensial cfg_tsc.py untuk memastikan kelima URL 404 itu halaman atau artikel,
dan apakah masih ada di trash sehingga bisa dipulihkan."""
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"}
print(f"   situs: {DOM} | user: {CFG['user']}")

COCOK = ["jadwal-dokter", "dermatologi-anak", "tahi-lalat", "klinik-dermatologi-terpercaya", "profil"]


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()), dict(x.headers)
        except urllib.error.HTTPError as e:
            return e.code, e.read().decode()[:200], {}
        except Exception:
            time.sleep(4)
    return 0, "gagal", {}


print("\n=== isi trash & draft untuk halaman dan artikel ===")
temuan = {}
for tipe in ("pages", "posts"):
    for status in ("trash", "draft", "pending", "private", "future", "publish"):
        st, d, h = rest(f"/wp-json/wp/v2/{tipe}?per_page=100&status={status}&_fields=id,slug,link,title,status,date")
        if not isinstance(d, list):
            print(f"   {tipe:<6} {status:<8} → HTTP {st} {str(d)[:60]}")
            continue
        cocok = [p for p in d if any(c in p.get("slug", "") for c in COCOK)]
        print(f"   {tipe:<6} {status:<8} → {len(d):>3} item | cocok: {len(cocok)}")
        for p in cocok:
            print(f"        COCOK {tipe[:-1]} [{status}] #{p['id']} /{p['slug']}")
            temuan.setdefault(p["slug"], []).append((tipe, status, p["id"]))
        # hitung total sebenarnya
        if h.get("X-WP-Total"):
            print(f"        total {status}: {h.get('X-WP-Total')}")

print("\n=== hasil: jenis konten untuk tiap URL yang 404 ===")
for slug in ("jadwal-dokter", "profil", "dermatologi-anak",
             "menghilangkan-tahi-lalat-laser-eksisi-atau-elektrokauter",
             "5-klinik-dermatologi-terpercaya-di-surabaya-untuk-perawatan-kulit"):
    ketemu = [v for k, v in temuan.items() if slug[:20] in k]
    if ketemu:
        for tipe, status, pid in ketemu[0]:
            print(f"   /{slug[:46]:<48} → {tipe[:-1].upper()} [{status}] #{pid}")
    else:
        print(f"   /{slug[:46]:<48} → tidak ada di database (kemungkinan dihapus permanen)")

print("\n=== ringkasan jumlah konten ===")
for tipe in ("pages", "posts"):
    for status in ("publish", "draft", "trash"):
        st, d, h = rest(f"/wp-json/wp/v2/{tipe}?per_page=1&status={status}&_fields=id")
        total = h.get("X-WP-Total") or (len(d) if isinstance(d, list) else "?")
        print(f"   {tipe:<6} {status:<8}: {total}")
