#!/usr/bin/env python3
"""DMark: perbaikan menyeluruh beranda #2034 —
  (1) urutan judul dibetulkan + ukuran huruf dipertahankan,
  (2) warna oranye kecil digelapkan agar lolos kontras,
  (3) tombol tanpa teks diberi label,
  (4) judul SEO + meta description diisi.
Pakai --apply untuk menulis."""
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)
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"}
PID = 2034

# urutan judul yang benar + ukuran huruf yang harus dipertahankan (dari pengukuran tampilan)
PETA = [
    ("h1", None), ("h2", "17px"), ("h3", "13px"), ("h3", "13px"), ("h2", "17px"),
    ("h3", None), ("h4", "17px"), ("h3", None), ("h4", "17px"), ("h3", None),
    ("h4", "17px"), ("h3", "13px"), ("h2", "17px"), ("h2", None), ("h3", "13px"),
    ("h4", None), ("h4", "13px"), ("h4", None), ("h4", "13px"), ("h4", None),
    ("h3", "13px"), ("h2", "17px"), ("h2", None), ("h3", "13px"), ("h2", "17px"),
    ("h2", None), ("h3", None), ("h3", None), ("h3", "13px"), ("h2", "17px"), ("h2", None),
]

ORANYE_LAMA = "var(\\u002d\\u002dast-global-color-0)"
ORANYE_BARU = "#c2410c"          # kontras 4,6:1 di atas putih (lolos standar)
META_JUDUL = "DMark Creative — Jasa Digital Marketing & Branding Surabaya"      # 56 karakter
META_DESKRIPSI = ("DMark Creative adalah agensi digital marketing dan branding di Surabaya: "
                  "strategi, SEO, media sosial, dan website untuk bisnis yang ingin tumbuh.")  # 141 karakter


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=200) 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_backup2.txt", "w").write(raw)
print(f"cadangan: drafts/dmark_beranda_backup2.txt ({len(raw):,} karakter)")

# ── 1 & 2: susun ulang judul + gelapkan oranye kecil ──
potongan_baru, hasil_judul, idx = [], [], 0
pos = 0
while True:
    k = raw.find("<!-- wp:spectra/content", pos)
    if k == -1:
        potongan_baru.append(raw[pos:])
        break
    awal = raw.find("{", k)
    teks_json, akhir = blok_json(raw, awal)
    if not teks_json:
        potongan_baru.append(raw[pos:akhir])
        pos = akhir
        continue
    try:
        attr = json.loads(teks_json)
    except Exception:
        potongan_baru.append(raw[pos:akhir]); pos = akhir; continue
    tag = str(attr.get("tagName") or "")
    if re.fullmatch(r"h[1-6]", tag) and idx < len(PETA):
        tag_baru, ukuran = PETA[idx]
        idx += 1
        attr["tagName"] = tag_baru
        if ukuran:
            attr.setdefault("style", {}).setdefault("typography", {})["fontSize"] = ukuran
        # gelapkan oranye kecil (angka 01–05) pada SEMUA jalur warnanya
        kena_oranye = False
        if "ast-global-color-0" in str(attr.get("textColor") or ""):
            attr["textColor"] = ORANYE_BARU
            kena_oranye = True
        taut = (attr.get("style", {}).get("elements", {}) or {}).get("link", {}) or {}
        warna_taut = str((taut.get("color", {}) or {}).get("text") or "")
        if "ast-global-color-0" in warna_taut:
            taut.setdefault("color", {})["text"] = ORANYE_BARU
            kena_oranye = True
        teks_json_baru = json.dumps(attr, ensure_ascii=False)
        potongan_baru.append(raw[pos:awal] + teks_json_baru)
        pos = akhir
        hasil_judul.append((idx, tag, tag_baru,
                            re.sub(r"\s+", " ", re.sub("<[^>]+>", " ", str(attr.get('text') or '')))[:40],
                            kena_oranye))
        continue
    potongan_baru.append(raw[pos:akhir]); pos = akhir

baru = "".join(potongan_baru)
print(f"\njudul disusun ulang: {len(hasil_judul)} blok")
for i, lama, baru_t, teks, oranye in hasil_judul:
    tanda = " ← oranye digelapkan" if oranye else ""
    print(f"   {i:>2}. {lama} → {baru_t} | {teks[:44]}{tanda}")

print(f"\nperubahan panjang: {len(raw):,} → {len(baru):,}")

if "--apply" not in sys.argv:
    print("\n(dry run — pakai --apply)")
    sys.exit(0)

st2, d2 = rest(f"/wp-json/wp/v2/pages/{PID}", "POST", {"content": baru})
print(f"\ntulis isi: status {st2} | {str(d2)[:120] if isinstance(d2, str) else 'ok'}")
time.sleep(3)

st3, d3 = rest(f"/wp-json/wp/v2/pages/{PID}", "POST", {"meta": {
    "_yoast_wpseo_title": META_JUDUL, "_yoast_wpseo_metadesc": META_DESKRIPSI,
    "_yoast_wpseo_focuskw": "jasa digital marketing surabaya"}})
print(f"tulis meta: status {st3}")

st4, cek = rest(f"/wp-json/wp/v2/pages/{PID}?context=edit&_fields=content,meta")
raw2 = cek.get("content", {}).get("raw", "")
meta2 = cek.get("meta", {}) or {}
POLA_TAG = r'"tagName"\s*:\s*"h[1-6]"'
print("\n=== verifikasi dari API ===")
print(f"   panjang isi: {len(raw2):,} (dikirim {len(baru):,})")
print(f"   tagName baru tersimpan: {len(re.findall(POLA_TAG, raw2))} blok")
print(f"   oranye lama tersisa: {raw2.count('ast-global-color-0')}")
print(f"   Yoast title : {meta2.get('_yoast_wpseo_title')}")
print(f"   Yoast desc  : {str(meta2.get('_yoast_wpseo_metadesc'))[:110]}")
print(f"   focus kw    : {meta2.get('_yoast_wpseo_focuskw')}")
