#!/usr/bin/env python3
"""DAS: (1) cek pemakaian warna #d02c35 di situs, (2) perbaiki 5 artikel yang nomor WA-nya salah.
Nomor baku DAS: 6285242380789 (0852-4238-0789)."""
import base64, html, json, os, re, sys, time, urllib.request, urllib.error, importlib.util

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 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36"}
BACKUP = f"{WS}/das_pemulihan/cta"
os.makedirs(BACKUP, exist_ok=True)
BENAR = "6285242380789"

print("=== 1. warna #d02c35 di situs ===")
for u in ("/", "/bengkel-spesialis-nissan-surabaya/", "/bengkel-spesialis-lexus-di-surabaya/"):
    try:
        h = urllib.request.urlopen(urllib.request.Request(f"https://{DOM}{u}", headers=UA), timeout=90).read().decode("utf-8", "replace")
        n = len(re.findall(r"d02c35", h, re.I))
        tema = sorted(set(re.findall(r"/wp-content/themes/([a-z0-9\-_]+)/", h)))
        print(f"   {u[:44]:<46} '#d02c35' {n:>3}x | tema: {tema}")
        if n:
            mm = re.search(r".{0,110}d02c35.{0,80}", h, re.I | re.S)
            print(f"      contoh: {re.sub(chr(10), ' ', mm.group(0))[:170]}")
    except Exception as e:
        print(f"   {u}: gagal {str(e)[:40]}")

PERBAIKAN = {
    7785: [("wa.me/6285242430789", f"wa.me/{BENAR}"), ("0852-4243-0789", "0852-4238-0789")],
    7263: [("wa.me/6281935000624", f"wa.me/{BENAR}")],
    7262: [("wa.me/6281935000624", f"wa.me/{BENAR}")],
    7261: [("wa.me/6281935000624", f"wa.me/{BENAR}")],
    5569: [("wa.me/6281909222026", f"wa.me/{BENAR}")],
}


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"


print("\n=== 2. perbaikan nomor WA ===")
for pid, daftar in PERBAIKAN.items():
    st, p = rest(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=id,slug,link,content")
    if not isinstance(p, dict) or "__err" in str(p)[:20]:
        print(f"   #{pid}: gagal baca ({st})")
        continue
    raw = p.get("content", {}).get("raw", "")
    open(f"{BACKUP}/post_{pid}.txt", "w").write(raw)
    baru, n = raw, 0
    for lama, gant in daftar:
        if lama in baru:
            n += baru.count(lama)
            baru = baru.replace(lama, gant)
    if n == 0:
        print(f"   #{pid} /{p['slug'][:40]}: tidak ada yang cocok (sudah benar?)")
        continue
    if "--apply" in sys.argv:
        rest(f"/wp-json/wp/v2/posts/{pid}", "POST", {"content": baru})
        _, cek = rest(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=content")
        raw2 = cek.get("content", {}).get("raw", "") if isinstance(cek, dict) else ""
        sisa_salah = [no for no in ("6281935000624", "6281909222026", "6285242430789") if no in raw2]
        print(f"   #{pid} /{p['slug'][:38]:<40} {n} penggantian | sisa nomor salah: {sisa_salah or 'tidak ada'} | "
              f"nomor benar muncul {raw2.count(BENAR)}x | cocok: {'✅' if raw2 == baru else '⚠️'}")
    else:
        print(f"   #{pid} /{p['slug'][:38]:<40} {n} penggantian siap (dry run)")
print(f"\n(dry run — pakai --apply untuk menyimpan)" if "--apply" not in sys.argv else "")
