#!/usr/bin/env python3
"""DMark: ekstrak blok judul dengan penyeimbang kurung (JSON bersarang)."""
import json, re
from collections import Counter

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
raw = open(f"{WS}/drafts/dmark_beranda_asli.txt").read()


def blok_json(teks, mulai):
    """Ambil objek JSON mulai dari posisi '{' dengan menghitung kurung."""
    if teks[mulai] != "{":
        return None, mulai
    dalam_string = False
    lepas = False
    level = 0
    i = mulai
    while i < len(teks):
        ch = teks[i]
        if dalam_string:
            if lepas:
                lepas = False
            elif ch == "\\":
                lepas = True
            elif ch == '"':
                dalam_string = False
        else:
            if ch == '"':
                dalam_string = True
            elif ch == "{":
                level += 1
            elif ch == "}":
                level -= 1
                if level == 0:
                    return teks[mulai:i + 1], i + 1
        i += 1
    return None, i


judul = []
pos = 0
while True:
    k = raw.find("<!-- wp:spectra/content", pos)
    if k == -1:
        break
    awal = raw.find("{", k)
    potongan, akhir = blok_json(raw, awal)
    pos = akhir
    if not potongan:
        continue
    try:
        attr = json.loads(potongan)
    except Exception:
        continue
    tag = str(attr.get("tagName") or "")
    if re.fullmatch(r"h[1-6]", tag):
        teks = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", str(attr.get("text") or ""))).strip()
        judul.append({"tag": tag, "teks": teks[:64], "attr": attr, "mentah": potongan})

print(f"total blok judul: {len(judul)}\n")
for i, j in enumerate(judul, 1):
    gaya = j["attr"].get("style", {}) or {}
    warna = json.dumps(gaya.get("color") or {})
    elemen = json.dumps(gaya.get("elements") or {})
    tipo = json.dumps(gaya.get("typography") or {})
    print(f"{i:>2}. <{j['tag']}> {j['teks'][:56]:<58}")
    if warna != "{}":
        print(f"      warna   : {warna[:110]}")
    if elemen != "{}":
        print(f"      elemen  : {elemen[:110]}")
    if tipo != "{}":
        print(f"      tipografi: {tipo[:110]}")

print("\nsebaran tag:", Counter(j["tag"] for j in judul))
json.dump([{"i": i, "tag": j["tag"], "teks": j["teks"]} for i, j in enumerate(judul, 1)],
          open(f"{WS}/drafts/dmark_judul.json", "w"), indent=1, ensure_ascii=False)
