#!/usr/bin/env python3
"""Bersihkan tautan tak terlihat (<a href="..."></a>) di seluruh isi StudioSoft.

Tautan seperti ini tidak terlihat pembaca, tidak punya fungsi apa pun, dan biasa dipakai untuk
menitipkan tautan ke situs lain. Aman dihapus: teks yang terlihat tidak berubah sama sekali.

Jalankan tanpa argumen = uji. Dengan --go = kerjakan (dengan cadangan).
"""
import base64, json, re, sys, time, urllib.request

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
S = "https://studiosoft.id"
A = base64.b64encode(b"bambangbot:q26r RePo BVy6 pwU2 F3z7 ouyl").decode()
H = {"Authorization": f"Basic {A}", "User-Agent": "Mozilla/5.0", "Content-Type": "application/json"}
UA = {"User-Agent": "Mozilla/5.0"}
KOSONG = re.compile(r'<a\b[^>]*>\s*</a>', re.S)
GO = "--go" in sys.argv

data = json.load(open(f"{WS}/drafts/ss_tautan_mencurigakan.json"))
per_entri = {}
for jenis, pid, slug, u in data["kosong"]:
    per_entri.setdefault((jenis, pid), {"slug": slug, "url": []})
    per_entri[(jenis, pid)]["url"].append(u)
print(f"tautan tak terlihat: {len(data['kosong'])} buah di {len(per_entri)} artikel/halaman\n")


def rest(p, method="GET", payload=None, ulang=3):
    body = json.dumps(payload).encode() if payload is not None else None
    akhir = ""
    for i in range(ulang):
        try:
            r = urllib.request.Request(S + p, data=body, headers=H, method=method)
            with urllib.request.urlopen(r, timeout=150) as x:
                return json.loads(x.read())
        except Exception as e:
            akhir = str(e)[:40]
            time.sleep(5 + i * 5)
    raise RuntimeError(akhir)


cadangan, total = {}, 0
for (jenis, pid), info in sorted(per_entri.items()):
    try:
        isi = rest(f"/wp-json/wp/v2/{jenis}/{pid}?context=edit&_fields=content")["content"]["raw"]
    except Exception as e:
        print(f"   #{pid} gagal ambil: {e}")
        continue
    n = len(KOSONG.findall(isi))
    if not n:
        continue
    baru = KOSONG.sub("", isi)

    def bersih(h):
        t = re.sub(r"<[^>]+>", " ", h)
        t = t.replace("\u200b", "").replace("\ufeff", "").replace("&nbsp;", " ")
        return re.sub(r"\s+", " ", t).strip()

    aman = bersih(isi) == bersih(baru)
    print(f"   #{pid} [{jenis}] {info['slug'][:44]:<46} {n} tautan tak terlihat "
          f"· teks {'tetap' if aman else '⚠ BERUBAH'}")
    total += n
    cadangan[f"{jenis}:{pid}"] = isi
    if GO and aman:
        try:
            rest(f"/wp-json/wp/v2/{jenis}/{pid}", "POST", {"content": baru})
        except Exception as e:
            print(f"        gagal simpan: {e}")
        time.sleep(0.6)

if GO:
    json.dump(cadangan, open(f"{WS}/ss_backup_tautan_tak_terlihat.json", "w"), ensure_ascii=False)
    print(f"\n✅ {total} tautan tak terlihat dihapus · cadangan: ss_backup_tautan_tak_terlihat.json")
else:
    print(f"\n(uji) {total} tautan tak terlihat siap dihapus. Pakai --go untuk mengerjakan.")
