#!/usr/bin/env python3
"""TSC — ganti nomor WhatsApp lama di seluruh konten + ubah label tombol ke The Skin Code Clinic.

Perintah Bos 7 Okt 2026: "cek 6285194936363 ganti semua no itu dengan 6285117444417.
Ganti label ke The Skin Code Clinic".

Yang diubah hanya di dalam tautan WhatsApp (wa.me / api.whatsapp.com):
  - nomor 6285194936363 dan 6281335114324  → 6285117444417
  - teks tombol "Klinik DNI Krian"         → "The Skin Code Clinic"

Salinan isi setiap halaman disimpan lebih dulu. Pakai --go untuk menulis.
"""
import base64, html, importlib.util, json, os, re, sys, time, urllib.error, urllib.request

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
BACKUP = f"{WS}/tsc_backup_nomor"
os.makedirs(BACKUP, exist_ok=True)

spec = importlib.util.spec_from_file_location("cfg", f"{WS}/cfg_tsc.py")
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
CFG = m.CFG
DOM = CFG["domain"]
AUTH = base64.b64encode(f"{CFG['user']}:{CFG['pass']}".encode()).decode()
UA = {"User-Agent": "Mozilla/5.0"}

NOMOR_BARU = "6285117444417"
NOMOR_LAMA = ["6285194936363", "6281335114324"]
LABEL = [
    ("Klinik%20DNI%20Krian", "The%20Skin%20Code%20Clinic"),
    ("Klinik+DNI+Krian", "The+Skin+Code+Clinic"),
    ("klinik%20dni%20krian", "the%20skin%20code%20clinic"),
    ("Klinik DNI Krian", "The Skin Code Clinic"),
    ("klinik dni krian", "The Skin Code Clinic"),
]
POLA_TOMBOL = re.compile(r"<a[^>]*?(?:wa\.me|api\.whatsapp)[^>]*>.*?</a>", re.S)


def rest(path, 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}{path}", 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"


daftar = json.load(open(f"{WS}/drafts/tsc_nomor_lama_di_konten.json"))
print(f"konten yang akan diperiksa: {len(daftar)}")


def ubah(raw):
    """kembalikan (teks_baru, jumlah_nomor, jumlah_label)"""
    n_nomor = [0]
    n_label = [0]

    def ganti_tombol(mo):
        t = mo.group(0)
        for lama in NOMOR_LAMA:
            n = t.count(lama)
            if n:
                n_nomor[0] += n
                t = t.replace(lama, NOMOR_BARU)
        for dari, ke in LABEL:
            n = t.count(dari)
            if n:
                n_label[0] += n
                t = t.replace(dari, ke)
        return t

    return POLA_TOMBOL.sub(ganti_tombol, raw), n_nomor[0], n_label[0]


go = "--go" in sys.argv
total_nomor = total_label = 0
diubah = []
for d in daftar:
    st, o = rest(f"/wp-json/wp/v2/{d['jenis']}/{d['id']}?context=edit&_fields=id,content,link,title")
    if not isinstance(o, dict) or "content" not in o:
        print(f"  ❌ #{d['id']} baca gagal {st}")
        continue
    raw = o["content"]["raw"]
    baru, n_nomor, n_label = ubah(raw)
    if not (n_nomor or n_label):
        continue
    total_nomor += n_nomor
    total_label += n_label
    diubah.append({"jenis": d["jenis"], "id": d["id"], "link": d["link"],
                   "nomor": n_nomor, "label": n_label})
    print(f"  #{d['id']:<6} {d['jenis']:<6} nomor {n_nomor} · label {n_label} | {html.unescape(str(o.get('title', {}).get('raw', '')))[:50]}")
    if go:
        open(f"{BACKUP}/{d['jenis']}_{d['id']}.txt", "w").write(raw)
        st2, _ = rest(f"/wp-json/wp/v2/{d['jenis']}/{d['id']}", "POST", {"content": baru})
        time.sleep(0.4)
        if st2 != 200:
            print(f"     ❌ tulis gagal HTTP {st2}")

print(f"\ntotal: {len(diubah)} konten · {total_nomor} nomor diganti · {total_label} label diganti")
json.dump(diubah, open(f"{WS}/drafts/tsc_perubahan_nomor.json", "w"), ensure_ascii=False, indent=1)
if not go:
    print("\n(dry run — pakai --go)")
else:
    print(f"\nsalinan sebelum perubahan: {BACKUP}/")
