#!/usr/bin/env python3
"""TSC: survei SEMUA tautan WhatsApp di situs — isi artikel, halaman, dan HTML yang dirender."""
import base64, html, json, os, 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 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36"}
TARGET = "https://api.whatsapp.com/send/?phone=%206285194936363&text=Saya+ingin+konsultasi+masalah+kulit+di+Klinik+DNI+Krian&type=phone_number&app_absent=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 []


print("=== 1. tautan WA di isi artikel (167 artikel) ===")
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

POLA = re.compile(r"https?://(?:api\.whatsapp\.com/send/\?[^\"'<>\s]*|wa\.me/[\d]+[^\"'<>\s]*)")
hitung_bentuk = Counter()
per_artikel = {}
for p in posts:
    raw = p.get("content", {}).get("raw", "")
    tautan = POLA.findall(raw)
    if not tautan:
        per_artikel[p["id"]] = []
        continue
    per_artikel[p["id"]] = tautan
    for t in tautan:
        nomor = re.search(r"phone=%20?(\d+)|wa\.me/(\d+)", t)
        kunci = ("api.whatsapp.com" if "api.whatsapp.com" in t else "wa.me",
                 (nomor.group(1) or nomor.group(2)) if nomor else "?")
        hitung_bentuk[kunci] += 1

print(f"   {len(posts)} artikel diperiksa | {sum(1 for v in per_artikel.values() if v)} punya tautan WA")
for (jenis, nomor), n in hitung_bentuk.most_common():
    tanda = " ← TARGET" if nomor == "6285194936363" else ""
    print(f"   {jenis:<18} nomor {nomor:<16} {n}x{tanda}")
tanpa_wa = [pid for pid, v in per_artikel.items() if not v]
print(f"   artikel TANPA tautan WA: {len(tanpa_wa)} → {tanpa_wa[:12]}")

print("\n=== 2. persis sama dengan target? ===")
cocok = sum(1 for v in per_artikel.values() for t in v if html.unescape(t) == TARGET or t == TARGET)
print(f"   tautan yang identik dengan target: {cocok}")

print("\n=== 3. tautan WA di halaman & HTML yang dirender ===")
for u in ("/", "/tentang-kami/", "/articles/", "/clients/"):
    try:
        h = urllib.request.urlopen(urllib.request.Request(f"https://www.{DOM}{u}", headers=UA), timeout=90).read().decode("utf-8", "replace")
        taut = re.findall(r'href="([^"]*(?:wa\.me|api\.whatsapp\.com)[^"]*)"', h)
        unik = sorted(set(html.unescape(t) for t in taut))
        print(f"   {u:<16} {len(unik)} tautan unik")
        for t in unik[:4]:
            nomor = re.search(r"phone=%20?(\d+)|wa\.me/(\d+)", t)
            print(f"        {('SAMA' if t == TARGET else 'beda')} | nomor {(nomor.group(1) or nomor.group(2)) if nomor else '?'} | {t[:78]}")
    except Exception as e:
        print(f"   {u}: gagal {str(e)[:50]}")
