#!/usr/bin/env python3
"""DMark: uji ubah SATU blok judul (h5 → h2) sambil mempertahankan ukuran huruf.
Kalau berhasil, baru diterapkan ke seluruh beranda."""
import base64, json, re, sys, 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()[:250]
        except Exception:
            time.sleep(4)
    return 0, "gagal"


def blok_json(teks, mulai):
    if teks[mulai] != "{":
        return None, mulai
    dalam, lepas, level, i = False, False, 0, mulai
    while i < len(teks):
        ch = teks[i]
        if dalam:
            if lepas:
                lepas = False
            elif ch == "\\":
                lepas = True
            elif ch == '"':
                dalam = False
        else:
            if ch == '"':
                dalam = True
            elif ch == "{":
                level += 1
            elif ch == "}":
                level -= 1
                if level == 0:
                    return teks[mulai:i + 1], i + 1
        i += 1
    return None, i


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

# cari blok h5 "Creativity is Intelegence Having Fun" (judul kutipan, ukuran tampil 17px)
target = "Creativity is Intelegence"
pos, baru = 0, raw
ketemu = False
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 or target not in potongan:
        continue
    attr = json.loads(potongan)
    print(f"\nsebelum : tagName={attr.get('tagName')} | style={json.dumps(attr.get('style'))[:160]}")
    attr["tagName"] = "h2"
    gaya = attr.setdefault("style", {})
    gaya.setdefault("typography", {})["fontSize"] = "17px"
    baru_attr = json.dumps(attr, ensure_ascii=False)
    baru = raw[:awal] + baru_attr + raw[akhir:]
    ketemu = True
    print(f"sesudah : tagName={attr.get('tagName')} | typography={json.dumps(gaya['typography'])[:120]}")
    break

if not ketemu:
    print("blok target tidak ditemukan"); sys.exit(1)

if "--tulis" in sys.argv:
    st2, d2 = rest(f"/wp-json/wp/v2/pages/{PID}", "POST", {"content": baru})
    print(f"\ntulis: status {st2}")
    time.sleep(3)
    st3, cek = rest(f"/wp-json/wp/v2/pages/{PID}?context=edit&_fields=content")
    raws2 = cek["content"]["raw"]
    print(f"  cocok dengan yang dikirim: {raws2 == baru} | panjang {len(raws2):,}")
    print(f"  tagName tersimpan: {re.search(r'Creativity is Intelegence.{0,900}?tagName', raws2).group(0)[:60] if 'Creativity is Intelegence' in raws2 else '-'}")
else:
    print("\n(dry run — pakai --tulis untuk menyimpan)")
