#!/usr/bin/env python3
"""DAS: baca Site Title & Tagline yang berlaku sekarang + di mana keduanya tampil."""
import base64, html, json, re, urllib.request, importlib.util

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg_das", f"{WS}/cfg_das.py")
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
CFG = m.CFG
DOM = CFG["domain"]
AUTH = base64.b64encode(f'{CFG["user"]}:{CFG["pass"]}'.encode()).decode()
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36"}


def rest(p):
    r = urllib.request.Request(f"https://{DOM}{p}", headers={"Authorization": f"Basic {AUTH}", **UA})
    with urllib.request.urlopen(r, timeout=120) as x:
        return json.loads(x.read())


print("=== 1. pengaturan situs (Settings → General) ===")
try:
    s = rest("/wp-json/wp/v2/settings")
    for k in ("title", "description", "url", "timezone", "posts_per_page", "language"):
        if k in s:
            print(f"   {k:<16}: {str(s[k])[:90]}")
except Exception as e:
    print("   gagal:", str(e)[:90])

print("\n=== 2. yang tampil di beranda ===")
h = urllib.request.urlopen(urllib.request.Request(f"https://{DOM}/", headers=UA), timeout=90).read().decode("utf-8", "replace")
t = re.search(r"<title>(.*?)</title>", h, re.S)
d = re.search(r'<meta name="description" content="([^"]*)"', h)
print(f"   <title>          : {html.unescape(t.group(1)).strip() if t else '-'}")
print(f"   meta description : {html.unescape(d.group(1))[:120] if d else '-'}")
for pola, nama in ((r'class="site-title"[^>]*>(.*?)</', "site-title (header)"),
                   (r'class="site-description"[^>]*>(.*?)</', "site-description (tagline)"),
                   (r'<footer.*?</footer>', "footer")):
    mm = re.search(pola, h, re.S | re.I)
    if mm:
        isi = re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", mm.group(1) if mm.lastindex else mm.group(0))))
        print(f"   {nama:<26}: {isi.strip()[:130]}")
    else:
        print(f"   {nama:<26}: (tidak ditemukan di HTML)")

print("\n=== 3. apa yang dipakai Yoast untuk judul beranda ===")
try:
    y = json.loads(urllib.request.urlopen(urllib.request.Request(f"https://{DOM}/wp-json/yoast/v1/get_head?url=https://{DOM}/", headers=UA), timeout=90).read())
    j = y.get("json") or {}
    print(f"   judul Yoast : {j.get('title')}")
    print(f"   site_name   : {(j.get('@graph') or [{}])[0].get('name') if j.get('@graph') else '-'}")
except Exception as e:
    print("   gagal:", str(e)[:80])
