#!/usr/bin/env python3
"""DMark: verifikasi hasil uji — cek atribut blok di API dan ukuran tampilannya di halaman."""
import asyncio, base64, json, re, time, urllib.request, 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)
DOM = m.CFG.get("domain", "www.dmark.id")
AUTH = base64.b64encode(f'{m.CFG["user"]}:{m.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:
            time.sleep(4)
    return []


raw = rest("/wp-json/wp/v2/pages/2034?context=edit&_fields=content")["content"]["raw"]
i = raw.find("Creativity is Intelegence")
print("=== atribut blok kutipan menurut API ===")
print("   " + re.sub(r"\s+", " ", raw[max(0, i - 320):i + 60])[:420])


async def ukur():
    from playwright.async_api import async_playwright
    async with async_playwright() as pw:
        br = await pw.chromium.launch()
        hal = await br.new_page(viewport={"width": 1440, "height": 1000})
        await hal.goto("https://www.dmark.id/", wait_until="domcontentloaded", timeout=120000)
        await hal.wait_for_timeout(5000)
        hasil = await hal.evaluate("""
        () => Array.from(document.querySelectorAll('h1,h2,h3,h4,h5,h6')).map(el => {
            const cs = getComputedStyle(el);
            return {tag: el.tagName.toLowerCase(), text: (el.innerText||'').replace(/\\s+/g,' ').trim().slice(0,44),
                    size: cs.fontSize, weight: cs.fontWeight, color: cs.color};
        })""")
        print(f"\n=== urutan judul di halaman ({len(hasil)}) ===")
        urut = []
        for h in hasil[:12]:
            print(f"   <{h['tag']}> {h['text'][:44]:<46} {h['size']:>7} / {h['weight']} / {h['color']}")
        for h in hasil:
            urut.append(h["tag"])
        # periksa lompatan level
        angka = [int(t[1]) for t in urut]
        lompat = [(i, urut[i-1], urut[i]) for i in range(1, len(angka)) if angka[i] - angka[i-1] > 1]
        print(f"\n   lompatan level: {len(lompat)}")
        for l in lompat[:10]:
            print(f"      {l[1]} → {l[2]}")
        await br.close()


asyncio.run(ukur())
