#!/usr/bin/env python3
"""Perbaiki tautan WhatsApp yang punya spasi setelah 'phone=' di konten TSC (mis. phone= 6285...)."""
import base64, 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"}

POLA = re.compile(r"(phone=)(%20|\+| )(?=62\d{9,13})")


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


go = "--go" in sys.argv
jumlah = 0
for jenis in ("posts", "pages"):
    page = 1
    while True:
        st, d = rest(f"/wp-json/wp/v2/{jenis}?per_page=100&page={page}&status=publish&context=edit"
                     f"&_fields=id,slug,link,content")
        if not isinstance(d, list) or not d:
            break
        for x in d:
            raw = x["content"]["raw"]
            if not POLA.search(raw):
                continue
            baru = POLA.sub(r"\1", raw)
            n = len(POLA.findall(raw))
            jumlah += 1
            print(f"  #{x['id']:<6} {jenis:<6} {n} tautan spasi → {x['link'][:64]}")
            if go:
                open(f"{BACKUP}/{jenis}_{x['id']}_spasi.txt", "w").write(raw)
                st2, _ = rest(f"/wp-json/wp/v2/{jenis}/{x['id']}", "POST", {"content": baru})
                time.sleep(0.3)
                print(f"        HTTP {st2}")
        if len(d) < 100:
            break
        page += 1

print(f"\nkonten dengan tautan berspasi: {jumlah}")
if not go:
    print("(dry run — pakai --go)")
