#!/usr/bin/env python3
"""DMark: daftar semua blok spectra/content yang berupa judul (h1-h6) di beranda, beserta warna & ukurannya."""
import base64, json, re, time, urllib.request, time as t2, 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):
    r = urllib.request.Request(f"https://{DOM}{p}", headers={"Authorization": f"Basic {AUTH}", **UA})
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=180) as x:
                return json.loads(x.read())
        except Exception:
            t2.sleep(4)
    return []


raw = rest("/wp-json/wp/v2/pages/2034?context=edit&_fields=content")["content"]["raw"]
open(f"{WS}/drafts/dmark_beranda_asli.txt", "w").write(raw)
print(f"isi beranda disimpan: drafts/dmark_beranda_asli.txt ({len(raw):,} karakter)")

print("\n=== blok judul (spectra/content dengan tagName h1-h6) ===")
pola = re.compile(r'<!--\s*wp:spectra/content\s*(\{.*?\})\s*-->', re.S)
n = 0
for mm in pola.finditer(raw):
    try:
        attr = json.loads(mm.group(1))
    except Exception:
        continue
    tag = attr.get("tagName")
    if not tag or not re.fullmatch(r"h[1-6]", tag):
        continue
    n += 1
    teks = re.sub(r"<[^>]+>", " ", str(attr.get("text") or ""))
    teks = re.sub(r"\s+", " ", teks).strip()[:60]
    warna = json.dumps(attr.get("style", {}).get("color") or
                       attr.get("style", {}).get("elements", {}).get("link", {}).get("color") or {})
    tipografi = json.dumps(attr.get("style", {}).get("typography") or {})
    warna_bg = json.dumps(attr.get("backgroundColor") or (attr.get("style", {}) or {}).get("color", {}).get("background") or {})
    print(f"   {n:>2}. <{tag}> {teks[:52]:<54} warna={warna[:60]} bg={warna_bg[:40]}")
    if "font-size" in tipografi or "lineHeight" in tipografi:
        print(f"        tipografi: {tipografi[:120]}")
print(f"\ntotal blok judul: {n}")
