#!/usr/bin/env python3
"""Bersihkan isi TSC: hapus tautan spam tersembunyi, seragamkan nomor WA, betulkan placeholder.

Temuan: beranda memuat div tersembunyi (posisi di luar layar) berisi tautan judi, plus tautan
WhatsApp bernomor lama, dan satu artikel memakai nomor placeholder 0812-XXXX-XXXX.

Pakai --go untuk menjalankan (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_spam"
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"}

SPAM = ["bohocasino", "moonwin", "jeetcity", "jeet-city", "winorio", "sasjen", "zonnepaneelconcurrent",
        "1883magazine", "engineeringimpact"]
NOMOR_BARU = "6285117444417"
GANTI = [
    (re.compile(r"0?812[\s\-]*[Xx]{2,}[\s\-]*[Xx]{2,}"), "0851-1744-4417"),
    (re.compile(r"(?:https?:)?//wa\.me/6281335114324"), "https://wa.me/" + NOMOR_BARU),
    (re.compile(r"6281335114324"), NOMOR_BARU),
    (re.compile(r"6285194936363"), NOMOR_BARU),
]


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 i in range(4):
        try:
            with urllib.request.urlopen(r, timeout=120) as x:
                return x.status, json.loads(x.read())
        except urllib.error.HTTPError as e:
            if e.code in (429, 404):
                time.sleep(4 * (i + 1))
                continue
            return e.code, e.read().decode()[:180]
        except Exception:
            time.sleep(4)
    return 0, "gagal"


def buang_spam(raw):
    """hapus seluruh blok <div ...>...</div> yang memuat tautan spam"""
    jumlah = [0]

    def buang(mo):
        isi = mo.group(0)
        if any(s in isi.lower() for s in SPAM):
            jumlah[0] += 1
            return ""
        return isi

    baru = re.sub(r"<div[^>]*>.*?</div>", buang, raw, flags=re.S | re.I)
    return baru, jumlah[0]


go = "--go" in sys.argv
total_spam = 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,link,content")
        if not isinstance(d, list) or not d:
            break
        for x in d:
            raw = x["content"]["raw"]
            ada_spam = any(s in raw.lower() for s in SPAM)
            n_nomor = sum(len(p.findall(raw)) for p, _ in GANTI[:2])   # placeholder & nomor lama
            n_orang = sum(len(p.findall(raw)) for p, _ in GANTI[2:])
            if not (ada_spam or n_nomor or n_orang):
                continue
            baru, n_spam = buang_spam(raw)
            for pola, ke in GANTI:
                baru = pola.sub(ke, baru)
            print(f"  #{x['id']:<6} {jenis:<6} spam {n_spam} blok · nomor {n_nomor + n_orang} | {x['link'][:58]}", flush=True)
            total_spam += n_spam
            total_ganti += n_nomor + n_orang
            if go:
                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}", flush=True)
                time.sleep(1.5)
        if len(d) < 100:
            break
        page += 1
        time.sleep(0.5)

print(f"\nblok spam dibuang: {total_spam} · nomor diperbaiki: {total_ganti}")
if not go:
    print("(dry run — pakai --go)")

# daftar pengguna (indikasi akun asing)
if "--go" in sys.argv:
    st, u = rest("/wp-json/wp/v2/users?per_page=50&_fields=id,name,slug,roles,registered_date")
    print("\npengguna situs:")
    if isinstance(u, list):
        for x in u:
            print(f"   #{x['id']} {x['name'][:26]:<28} {x.get('roles')} · {str(x.get('registered_date'))[:10]}")
    else:
        print("   gagal membaca daftar pengguna:", str(u)[:80])
