#!/usr/bin/env python3
"""Cari semua penyebutan akun Instagram lama (@klinikdnikrian) di konten TSC, lalu ganti.

Pakai --go untuk menulis. Salinan isi disimpan lebih dulu.
"""
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_akun"
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"}

LAMA = re.compile(r"@\s*klinikdnikrian\b", re.I)
BARU = "@theskincode_clinic"
LAIN = re.compile(r"klinikdnikrian", re.I)   # bentuk lain, hanya dilaporkan


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
total_ganti = 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,title,content")
        if not isinstance(d, list) or not d:
            break
        for x in d:
            raw = x["content"]["raw"]
            n_ganti = len(LAMA.findall(raw))
            n_lain = len([m2 for m2 in LAIN.finditer(raw) if not m2.group(0).startswith("@")])
            if not (n_ganti or n_lain):
                continue
            print(f"\n  #{x['id']} {jenis} | {x['link'][:66]}")
            for mc in LAMA.finditer(raw):
                awal = max(0, mc.start() - 110)
                print(f"     GANTI  ... {re.sub(r'<[^>]+>', ' ', raw[awal:mc.end() + 60]).strip()[:150]}")
            for mc in LAIN.finditer(raw):
                if mc.group(0).startswith("@"):
                    continue
                awal = max(0, mc.start() - 90)
                print(f"     LAIN   ... {re.sub(r'<[^>]+>', ' ', raw[awal:mc.end() + 50]).strip()[:140]}")
            if n_ganti:
                total_ganti += n_ganti
                if go:
                    baru = LAMA.sub(BARU, raw)
                    open(f"{BACKUP}/{jenis}_{x['id']}.txt", "w").write(raw)
                    st2, _ = rest(f"/wp-json/wp/v2/{jenis}/{x['id']}", "POST", {"content": baru})
                    print(f"        → HTTP {st2}")
                    time.sleep(0.3)
        if len(d) < 100:
            break
        page += 1

print(f"\ntotal @klinikdnikrian ditemukan: {total_ganti}")
if not go:
    print("(dry run — pakai --go)")
else:
    print(f"salinan: {BACKUP}/")
