#!/usr/bin/env python3
"""DAS: lihat bentuk asli tombol yang belum berwarna (36) + tombol hijau (78) supaya tahu mana yang perlu diubah."""
import base64, json, os, re, time, urllib.request, importlib.util
from collections import Counter

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg_das", f"{WS}/cfg_das.py")
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
CFG = m.CFG
DOM, AUTH = CFG["domain"], 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:
            time.sleep(4)
    return []


posts, page = [], 1
while True:
    d = rest(f"/wp-json/wp/v2/posts?per_page=100&page={page}&status=publish&context=edit&_fields=id,slug,content")
    if not isinstance(d, list):
        break
    posts += d
    if len(d) < 100:
        break
    page += 1

tanpa_warna, hijau, merah = [], [], []
for p in posts:
    raw = p.get("content", {}).get("raw", "") or ""
    for mm in re.finditer(r'<a[^>]*>[^<]*AMBIL\s*PROMO[^<]*</a>', raw, re.I):
        el = mm.group(0)
        punya_inline = re.search(r"background-color", el, re.I)
        kelas = re.search(r'class="([^"]*)"', el)
        kls = kelas.group(1) if kelas else ""
        if punya_inline:
            continue
        if "vivid-green" in kls:
            hijau.append((p["id"], p["slug"], el))
        elif "vivid-red" in kls:
            merah.append((p["id"], p["slug"], el))
        else:
            tanpa_warna.append((p["id"], p["slug"], el))

print(f"tanpa warna: {len(tanpa_warna)} | hijau: {len(hijau)} | merah vivid: {len(merah)}\n")

print("=== 6 contoh tombol TANPA WARNA (apa adanya) ===")
for pid, slug, el in tanpa_warna[:6]:
    print(f"   #{pid}  {el[:190]}")

print("\n=== pola pembungkus tombol tanpa warna ===")
pola = Counter()
for pid, slug, el in tanpa_warna:
    if "<div class=\"wp-block-button" in el or 'class="wp-block-button__link"' in el:
        pola["blok tombol WP (punya kelas wp-block-button__link)"] += 1
    elif "<a " in el[:4]:
        pola["tautan biasa tanpa kelas"] += 1
    else:
        pola["lain-lain"] += 1
for k, v in pola.most_common():
    print(f"   {v:>3}x {k}")

print("\n=== 4 contoh tombol HIJAU ===")
for pid, slug, el in hijau[:4]:
    print(f"   #{pid}  {el[:200]}")
json.dump({"tanpa_warna": [x[0] for x in tanpa_warna], "hijau": [x[0] for x in hijau]},
          open(f"{WS}/drafts/das_tombol_sisa.json", "w"), indent=1)
