#!/usr/bin/env python3
"""TSLaw: sisir SEMUA nomor WhatsApp di artikel — cari yang bukan nomor resmi TSLaw."""
import base64, json, re, time, urllib.request, importlib.util
from collections import Counter, defaultdict

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"}
BENAR = "6281909222026"


def rest(p):
    r = urllib.request.Request(f"https://{DOM}{p}", headers={"Authorization": f"Basic {AUTH}", **UA})
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=180) as x:
                return json.loads(x.read())
        except Exception:
            time.sleep(4)
    return []


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

nomor = Counter()
tempat = defaultdict(list)
for p in posts:
    raw = (p.get("content") or {}).get("rendered", "") or ""
    teks = raw.replace("\u202a", "").replace("\u202c", "").replace("\u200e", "").replace("\u200f", "")
    for mm in re.finditer(r"(?:wa\.me/|api\.whatsapp\.com/send\?phone=|web\.whatsapp\.com/send\?phone=)([+%\d\s]{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
        nomor[n] += 1
        tempat[n].append(p["slug"])

print("\n=== nomor WhatsApp yang dipakai di artikel ===")
for n, c in nomor.most_common():
    tanda = " ✅ resmi" if n == BENAR else " ⚠️ BUKAN nomor TSLaw"
    print(f"   {n} → {c} tautan{tanda}")
    if n != BENAR:
        for s in tempat[n][:12]:
            print(f"        /{s[:70]}")

print("\n=== ringkas ===")
salah = sum(c for n, c in nomor.items() if n != BENAR)
print(f"   tautan ke nomor resmi : {nomor.get(BENAR, 0)}")
print(f"   tautan ke nomor lain  : {salah}")
print(f"   artikel terdampak     : {len({s for n, lst in tempat.items() if n != BENAR for s in lst})}")
