#!/usr/bin/env python3
"""TSLaw: seragamkan nomor WhatsApp di ARTIKEL — ganti nomor asing & nomor contoh jadi nomor resmi,
sekaligus buang karakter tak terlihat (U+202A/U+202C) yang bisa merusak tautan.
Halaman (page) TIDAK disentuh — hanya dilaporkan."""
import base64, json, os, re, sys, time, urllib.request, urllib.error, importlib.util

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg_tslaw", f"{WS}/cfg_tslaw.py")
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
DOM, AUTH = "www.tslaw.id", base64.b64encode(f'{m.CFG["user"]}:{m.CFG["pass"]}'.encode()).decode()
UA = {"User-Agent": "Mozilla/5.0"}
BACKUP = f"{WS}/tslaw_pemulihan/nomor"
os.makedirs(BACKUP, exist_ok=True)
BENAR = "6281909222026"
ASING = {"628113155454": "nomor tidak dikenal", "6281935000624": "nomor StudioSoft",
         "6281234567890": "nomor contoh"}


def rest(p, 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}{p}", data=body, headers=h, method=method)
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=200) 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(5)
    return 0, "gagal"


posts, page = [], 1
while True:
    st, d = rest(f"/wp-json/wp/v2/posts?per_page=100&page={page}&status=publish&context=edit&_fields=id,slug,content")
    if not isinstance(d, list):
        break
    posts += d
    if len(d) < 100:
        break
    page += 1

rencana = []
for p in posts:
    raw = p.get("content", {}).get("raw", "") or ""
    baru, aksi = raw, []
    for no, ket in ASING.items():
        if no in baru:
            aksi.append(f"{no} ({ket})")
            baru = baru.replace(no, BENAR)
    # buang karakter tak terlihat di dalam tautan wa.me
    if "\u202a" in baru or "\u202c" in baru or "%E2%80%AA" in baru or "%E2%80%AC" in baru:
        aksi.append("karakter tak terlihat")
        baru = baru.replace("\u202a", "").replace("\u202c", "").replace("\u200e", "").replace("\u200f", "")
        baru = baru.replace("%E2%80%AA", "").replace("%E2%80%AC", "")
    if baru != raw:
        rencana.append({"id": p["id"], "slug": p["slug"], "raw": raw, "baru": baru, "aksi": aksi})

print(f"artikel yang perlu dibetulkan: {len(rencana)}")
for r in rencana[:25]:
    print(f"   #{r['id']:>5} /{r['slug'][:52]:<54} {' + '.join(r['aksi'])}")

if "--apply" not in sys.argv:
    print("\n(dry run)")
    sys.exit(0)

ok = 0
for r in rencana:
    open(f"{BACKUP}/post_{r['id']}.txt", "w").write(r["raw"])
    rest(f"/wp-json/wp/v2/posts/{r['id']}", "POST", {"content": r["baru"]})
    st, cek = rest(f"/wp-json/wp/v2/posts/{r['id']}?context=edit&_fields=content")
    raw2 = (cek.get("content") or {}).get("raw", "") if isinstance(cek, dict) else ""
    sisa = [n for n in ASING if n in raw2]
    bagus = not sisa and "6281909222026" in raw2
    ok += 1 if bagus else 0
    print(f"   #{r['id']} {'✅' if bagus else '⚠️'} | sisa nomor asing: {sisa or 'tidak ada'}")
print(f"\nselesai: {ok}/{len(rencana)}")

print("\n=== verifikasi ulang seluruh artikel ===")
posts2 = []
page = 1
while True:
    st, d = rest(f"/wp-json/wp/v2/posts?per_page=100&page={page}&status=publish&context=view&_fields=id,slug,content")
    if not isinstance(d, list):
        break
    posts2 += d
    if len(d) < 100:
        break
    page += 1
from collections import Counter
c = Counter()
for p in posts2:
    raw = (p.get("content") or {}).get("rendered", "") or ""
    teks = re.sub(r"[\u202a\u202c\u200e\u200f]", "", raw)
    for mm in re.finditer(r"wa\.me/([+\d%]{6,25})", teks, re.I):
        n = re.sub(r"[^\d]", "", mm.group(1))
        if n.startswith("0"):
            n = "62" + n[1:]
        if not n.startswith("62"):
            n = "62" + n
        c[n] += 1
for n, j in c.most_common():
    print(f"   {n} → {j} tautan {'✅' if n == BENAR else '⚠️ masih ada'}")
