#!/usr/bin/env python3
"""TSC: tentukan jenis kelima URL yang 404 — halaman (page) atau artikel (post)?
Cek daftar terbit, draft, dan trash untuk kedua jenis konten."""
import base64, html, json, re, time, urllib.request, urllib.error

DOM = "theskincodeclinic.com"
UA = {"User-Agent": "Mozilla/5.0"}
COCOK = ["jadwal-dokter", "profil", "dermatologi-anak", "tahi-lalat", "klinik-dermatologi-terpercaya"]

# kredensial TSC: cek config klien
import os
kandidat_file = [f for f in os.listdir("/home/mantapman/.hermes/profiles/atun/workspace")
                 if f.startswith("cfg_") and "skin" in f.lower()]
print("berkas config TSC:", kandidat_file or "(tidak ada)")
if kandidat_file:
    isi = open(f"/home/mantapman/.hermes/profiles/atun/workspace/{kandidat_file[0]}").read()
    user = re.search(r'"user":\s*"([^"]+)"', isi)
    sandi = re.search(r'"pass":\s*"([^"]+)"', isi)
    print("user:", user.group(1) if user else "?", "| password ada:", bool(sandi))
    AUTH = base64.b64encode(f"{user.group(1)}:{sandi.group(1)}".encode()).decode() if user and sandi else None
else:
    AUTH = None

if not AUTH:
    print("\nTidak ada kredensial TSC di workspace — memakai REST publik untuk melihat jenis konten.")
    AUTH = ""


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


print("\n=== mencari slug di semua status ===")
for tipe in ("pages", "posts"):
    for status in ("publish", "draft", "pending", "private", "trash", "future"):
        st, d = rest(f"/wp-json/wp/v2/{tipe}?per_page=100&status={status}&_fields=id,slug,link,title,status")
        if not isinstance(d, list):
            continue
        temuan = [p for p in d if any(c in p.get("slug", "") for c in COCOK)]
        if temuan:
            for p in temuan:
                print(f"   {tipe[:-1].upper():<6} [{status:<7}] #{p['id']:>6} /{p['slug']}  {html.unescape(str(p.get('title', {}).get('rendered', '')))[:44]}")
        elif status == "trash":
            print(f"   {tipe[:-1]} trash: {len(d)} item (tidak ada yang cocok)")

print("\n=== berapa banyak halaman & artikel yang ada sekarang ===")
for tipe in ("pages", "posts"):
    for status in ("publish", "draft", "trash"):
        st, d = rest(f"/wp-json/wp/v2/{tipe}?per_page=100&status={status}&_fields=id")
        n = len(d) if isinstance(d, list) else f"err {st}"
        print(f"   {tipe:<6} {status:<8}: {n}")

print("\n=== daftar semua halaman (page) yang terbit ===")
st, d = rest("/wp-json/wp/v2/pages?per_page=100&_fields=id,slug,link,title")
if isinstance(d, list):
    for p in d:
        print(f"   #{p['id']:>6} {p['link'].replace(f'https://www.{DOM}', '')[:54]:<56} {html.unescape(p['title']['rendered'])[:34]}")
