#!/usr/bin/env python3
"""TSC: lihat BENTUK PERSIS setiap tautan WA di artikel (terutama yang nomornya belum terbaca)."""
import base64, json, re, time, urllib.request, importlib.util
from collections import Counter

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg_tsc", f"{WS}/cfg_tsc.py")
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
DOM, AUTH = m.CFG["domain"], base64.b64encode(f'{m.CFG["user"]}:{m.CFG["pass"]}'.encode()).decode()
UA = {"User-Agent": "Mozilla/5.0"}


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(3)
    return []


posts, page = [], 1
while True:
    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

bentuk = Counter()
contoh = {}
for p in posts:
    raw = p.get("content", {}).get("raw", "")
    for mm in re.finditer(r'href="([^"]*(?:api\.whatsapp\.com|wa\.me)[^"]*)"', raw):
        u = mm.group(1)
        # normalkan: ambil bagian nomor & text saja
        nomor = re.search(r"phone=([^&\"']+)|wa\.me/([^?\"']+)", u)
        jenis = "api.whatsapp.com" if "api.whatsapp" in u else "wa.me"
        kunci = f"{jenis} | nomor='{(nomor.group(1) or nomor.group(2)) if nomor else '?'}'"
        bentuk[kunci] += 1
        contoh.setdefault(kunci, (p["id"], u))

print("=== bentuk tautan WA di artikel ===")
for k, n in bentuk.most_common():
    pid, u = contoh[k]
    print(f"\n   {n:>3}x  {k}")
    print(f"        contoh (#{pid}): {u[:150]}")

print("\n=== teks (text=) yang dipakai ===")
tekss = Counter()
for p in posts:
    for t in re.findall(r"text=([^&\"']+)", p.get("content", {}).get("raw", "")):
        tekss[t[:80]] += 1
for t, n in tekss.most_common(8):
    print(f"   {n:>3}x  {t}")
