#!/usr/bin/env python3
"""DAS: tombol ber-kelas has-vivid-green-cyan-background-color → warna DAS #d02c35 (inline mengalahkan kelas).
Merah vivid + tanpa warna: dibiarkan (keputusan Bos). Teks tombol diseragamkan jadi 'AMBIL PROMO'."""
import base64, json, os, re, sys, time, urllib.request, urllib.error, 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"}
WARNA = "#d02c35"
BACKUP = f"{WS}/das_pemulihan/hijau2"
os.makedirs(BACKUP, exist_ok=True)

TEKS_GANTI = [(r">\s*AMBIL\s+PROMO\s*🔥\s*<", ">AMBIL PROMO<"),
              (r">\s*AMBIL\s\s+PROMO\s*<", ">AMBIL PROMO<"),
              (r">\s*KONSULTASI\s*&amp;\s*AMBIL\s*PROMO\s*<", ">AMBIL PROMO<"),
              (r">\s*KONSULTASI\s*&\s*AMBIL\s*PROMO\s*<", ">AMBIL PROMO<")]


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()[:200]
        except Exception:
            time.sleep(4)
    return 0, "gagal"


def perbaiki_tombol(raw):
    """Tambah/ubah warna inline #d02c35 pada tombol AMBIL PROMO yang berkelas hijau."""
    aksi, n = [], 0

    def ganti(mm):
        nonlocal n
        el = mm.group(0)
        if "vivid-green" not in el:
            return el
        n += 1
        if re.search(r'style="[^"]*background-color:[^;"]*', el, re.I):
            el = re.sub(r'(style="[^"]*background-color:)[^;"]*', rf"\g<1>{WARNA}", el, flags=re.I)
        elif 'style="' in el:
            el = el.replace('style="', f'style="background-color:{WARNA};', 1)
        else:
            el = el.replace("<a ", f'<a style="background-color:{WARNA}" ', 1)
        return el

    baru = re.sub(r'<a [^>]*>[^<]*AMBIL\s*PROMO[^<]*</a>', ganti, raw, flags=re.I)
    if n:
        aksi.append(f"hijau→merah {n}")
    return baru, aksi


posts, page = [], 1
while True:
    st, 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
print(f"artikel: {len(posts)}")

rencana = []
for p in posts:
    raw = p.get("content", {}).get("raw", "") or ""
    baru, aksi = perbaiki_tombol(raw)
    for pola, gant in TEKS_GANTI:
        if re.search(pola, baru):
            baru = re.sub(pola, gant, baru)
            if "teks" not in aksi:
                aksi.append("teks")
    if baru != raw:
        rencana.append({"id": p["id"], "slug": p["slug"], "raw": raw, "baru": baru, "aksi": aksi})

print(f"\nrencana: {len(rencana)} artikel")
c = Counter(a.split()[0] for r in rencana for a in r["aksi"])
for k, v in c.most_common():
    print(f"   {k:<12} {v} artikel")

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

ok = gagal = 0
for i, r in enumerate(rencana, 1):
    open(f"{BACKUP}/post_{r['id']}.txt", "w").write(r["raw"])
    rest(f"/wp-json/wp/v2/posts/{r['id']}", "POST", {"content": r["baru"]})
    _, cek = rest(f"/wp-json/wp/v2/posts/{r['id']}?context=edit&_fields=content")
    raw2 = cek.get("content", {}).get("raw", "") if isinstance(cek, dict) else ""
    ok, gagal = (ok + 1, gagal) if raw2 == r["baru"] else (ok, gagal + 1)
    if i % 20 == 0 or i == len(rencana):
        print(f"   {i}/{len(rencana)} | beres {ok} | gagal {gagal}")

print("\n=== verifikasi ===")
posts2, page = [], 1
while True:
    st, d = rest(f"/wp-json/wp/v2/posts?per_page=100&page={page}&status=publish&context=edit&_fields=id,content")
    if not isinstance(d, list):
        break
    posts2 += d
    if len(d) < 100:
        break
    page += 1
sisa = 0
for p in posts2:
    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)
        if "vivid-green" in el and WARNA not in el:
            sisa += 1
print(f"   tombol hijau belum berwarna DAS : {sisa}")
print(f"   artikel yang memuat {WARNA}   : {sum(1 for p in posts2 if WARNA in (p.get('content', {}).get('raw', '') or '').lower())}")
POLA_TEKS = r"AMBIL\s+PROMO\s*🔥|AMBIL\s\s+PROMO|KONSULTASI\s*&"
teks_sisa = sum(1 for p in posts2 if re.search(POLA_TEKS, p.get("content", {}).get("raw", "") or ""))
print(f"   teks tombol masih beda          : {teks_sisa}")
