#!/usr/bin/env python3
"""DMark: baca beranda (halaman depan) — struktur heading, warna teks, tautan kosong, dan meta Yoast."""
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_dmark", f"{WS}/cfg_dmark.py")
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
CFG = m.CFG
DOM = CFG.get("domain", "www.dmark.id")
AUTH = base64.b64encode(f'{CFG["user"]}:{CFG["pass"]}'.encode()).decode()
UA = {"User-Agent": "Mozilla/5.0"}


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()[:200]
        except Exception:
            time.sleep(4)
    return 0, "gagal"


print("=== halaman yang ada ===")
st, pages = rest("/wp-json/wp/v2/pages?per_page=100&context=edit&_fields=id,slug,link,title,meta,template")
if isinstance(pages, list):
    for p in pages:
        print(f"   #{p['id']:>4} /{p['slug']:<22} {html.unescape(re.sub('<[^>]+>','',p['title']['raw']))[:38]:<40} template={p.get('template') or '-'}")

print("\n=== setelan situs (page_on_front) ===")
st, s = rest("/wp-json/wp/v2/settings")
if isinstance(s, dict):
    print("   judul situs :", s.get("title"))
    print("   tagline     :", s.get("description"))
    print("   home page id:", s.get("page_on_front"), "| show_on_front:", s.get("show_on_front"))
else:
    print("   tidak bisa dibaca:", st, str(s)[:120])
