#!/usr/bin/env python3
"""DMark: periksa isi beranda #2034 — 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"}
PID = 2034


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"


st, p = rest(f"/wp-json/wp/v2/pages/{PID}?context=edit&_fields=id,slug,link,title,content,meta")
raw = p["content"]["raw"]
print(f"=== beranda #{PID} /{p['slug']} ===")
print(f"   panjang isi: {len(raw):,} karakter")
meta = p.get("meta") or {}
print(f"   Yoast title : {meta.get('_yoast_wpseo_title') or '(kosong)'}")
print(f"   Yoast desc  : {meta.get('_yoast_wpseo_metadesc') or '(kosong)'}")
print(f"   focus kw    : {meta.get('_yoast_wpseo_focuskw') or '(kosong)'}")

print("\n=== urutan heading di isi ===")
for i, mm in enumerate(re.finditer(r"<h([1-6])([^>]*)>(.*?)</h\1>", raw, re.S | re.I), 1):
    isi = html.unescape(re.sub(r"\s+", " ", re.sub(r"<[^>]+>", "", mm.group(3)))).strip()
    atribut = mm.group(2)
    gaya = re.search(r"style=\"([^\"]{0,120})\"", atribut)
    print(f"   {i:>2}. H{mm.group(1)} | {isi[:58]:<60} | {gaya.group(1)[:80] if gaya else ''}")

print("\n=== tautan dengan teks kosong atau href='#' ===")
for mm in re.finditer(r"<a ([^>]*)>(.*?)</a>", raw, re.S | re.I):
    teks = re.sub(r"<[^>]+>", "", mm.group(2)).strip()
    if not teks:
        print(f"   {mm.group(0)[:180]}")

print("\n=== blok dengan varian warna teks (untuk kontras) ===")
warna = re.findall(r"--spectra-text-color:\s*([^;\"]+)", raw)
from collections import Counter
print("   ", Counter(warna).most_common(8))
