#!/usr/bin/env python3
"""DAS: sisir SEMUA tautan WhatsApp di artikel + halaman + elemen tema (live).
Tujuan: pastikan tidak ada satu pun yang mengarah ke nomor milik website lain."""
import base64, html, json, re, time, urllib.request, urllib.error, importlib.util
from collections import Counter, defaultdict

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

# nomor milik klien lain yang sudah pernah ketemu
NOMOR_ASING = {"6281935000624": "StudioSoft", "6281909222026": "TSLaw", "6285194936363": "TSC",
               "6281234567890": "contoh", "628123456789": "contoh", "6281111111111": "contoh"}


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 []


def sisir(teks):
    """Ambil semua tautan WA + nomor yang tampak di dalamnya."""
    keluar = []
    for mm in re.finditer(r"(?:https?://)?(?:www\.)?(?:wa\.me|api\.whatsapp\.com/send|web\.whatsapp\.com/send|whatsapp\.com/send)[^\"'\s>)]*", teks, re.I):
        t = mm.group(0)
        no = re.search(r"(?:phone=|wa\.me/|/)(\+?\d[\d\s\-]{6,})", t)
        if no:
            bersih = re.sub(r"[^\d]", "", no.group(1))
            if bersih.startswith("0"):
                bersih = "62" + bersih[1:]
            keluar.append((bersih, t[:110]))
    # nomor gaya teks: "0852-4238-0789", "+62 852 4238 0789"
    for mm in re.finditer(r"(?:\+?62|0)8\d{2}[\s\-]?\d{3,4}[\s\-]?\d{3,5}", teks):
        bersih = re.sub(r"[^\d]", "", mm.group(0))
        if bersih.startswith("0"):
            bersih = "62" + bersih[1:]
        if bersih.startswith("8"):
            bersih = "62" + bersih
        keluar.append((bersih, "teks: " + mm.group(0)))
    return keluar


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


semua = {"posts": tarik("posts"), "pages": tarik("pages")}
print(f"artikel: {len(semua['posts'])} | halaman: {len(semua['pages'])}\n")

nomor_peta = defaultdict(list)
for jenis, daftar in semua.items():
    for p in daftar:
        raw = p.get("content", {}).get("raw", "") or ""
        for no, asal in sisir(raw):
            nomor_peta[no].append({"jenis": jenis, "id": p["id"], "slug": p["slug"], "asal": asal})

print("=== semua nomor WhatsApp yang dipakai di isi konten ===")
for no, tempat in sorted(nomor_peta.items(), key=lambda x: -len(x[1])):
    ket = f" ⚠️ MILIK {NOMOR_ASING[no]}" if no in NOMOR_ASING else ""
    print(f"   {no:<16} {len(tempat):>4} tempat{ket}")

print("\n=== rincian nomor yang BUKAN nomor DAS (6285242380789) ===")
temuan = False
for no, tempat in nomor_peta.items():
    if no == "6285242380789":
        continue
    temuan = True
    print(f"\n   {no}  ({'milik ' + NOMOR_ASING[no] if no in NOMOR_ASING else 'TIDAK DIKENAL'})")
    for t in tempat[:10]:
        print(f"      {t['jenis']:<6} #{t['id']:>5} /{t['slug'][:44]:<46} {t['asal'][:70]}")
if not temuan:
    print("   tidak ada ✅")

print("\n=== cek elemen tema di 6 halaman live (header/footer/tombol mengambang) ===")
for u in ("/", "/bengkel-spesialis-nissan-surabaya/", "/bengkel-spesialis-lexus-di-surabaya/",
          "/tentang-kami/", "/hubungi-kami/", "/blog/"):
    try:
        hh = urllib.request.urlopen(urllib.request.Request(f"https://{DOM}{u}?v={int(time.time())}", headers=UA), timeout=90).read().decode("utf-8", "replace")
        no = sorted({n for n, _ in sisir(hh)})
        jml_wa = len(re.findall(r"(?:wa\.me|api\.whatsapp\.com)", hh, re.I))
        print(f"   {u[:44]:<46} tautan WA {jml_wa:>2}x | nomor: {no if no else '-'}")
    except Exception as e:
        print(f"   {u[:44]:<46} GAGAL {str(e)[:40]}")
