#!/usr/bin/env python3
"""Cari semua tempat nomor WhatsApp tertentu muncul: di berkas workspace dan di halaman situs TSC."""
import os, re, sys, time, urllib.request, urllib.parse

NOMOR = sys.argv[1:] or ["6281335114324", "6285117444417", "6285194936363", "6281935000624"]
WS = "/home/mantapman/.hermes/profiles/atun/workspace"
DOM = "theskincodeclinic.com"
UA = {"User-Agent": "Mozilla/5.0 (compatible; AtunBot/1.0)"}

print("=== 1. di berkas workspace ===")
for akar, dirs, files in os.walk(WS):
    if any(x in akar for x in ("/.git", "/__pycache__", "/backup", "/Agentic-SEO-Skill")):
        continue
    for f in files:
        if not f.endswith((".py", ".md", ".json", ".txt", ".html", ".csv")):
            continue
        p = os.path.join(akar, f)
        try:
            if os.path.getsize(p) > 4_000_000:
                continue
            isi = open(p, errors="replace").read()
        except Exception:
            continue
        for n in NOMOR:
            if n in isi:
                baris = [i + 1 for i, l in enumerate(isi.splitlines()) if n in l]
                print(f"   {n} → {p.replace(WS, 'workspace')} (baris {baris[:4]}{'...' if len(baris) > 4 else ''})")

print("\n=== 2. di halaman situs theskincodeclinic.com ===")
try:
    sm = urllib.request.urlopen(urllib.request.Request(f"https://www.{DOM}/sitemap_index.xml", headers=UA),
                                timeout=90).read().decode("utf-8", "replace")
    sub = re.findall(r"<loc>([^<]+)</loc>", sm)
except Exception as e:
    print("   sitemap gagal:", str(e)[:80])
    sub = []
urls = []
for s in sub:
    try:
        x = urllib.request.urlopen(urllib.request.Request(s, headers=UA), timeout=90).read().decode("utf-8", "replace")
        urls += re.findall(r"<loc>([^<]+)</loc>", x)
    except Exception:
        continue
urls = sorted(set(u for u in urls if u.startswith("http")))
print(f"   {len(urls)} URL dari sitemap, diperiksa satu per satu...")

temuan = {}
for i, u in enumerate(urls, 1):
    try:
        t = urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=45).read().decode("utf-8", "replace")
    except Exception as e:
        temuan[u] = f"GAGAL {str(e)[:30]}"
        continue
    kena = [n for n in NOMOR if n in t or f"wa.me/{n}" in t or f"phone={n}" in t]
    if kena:
        temuan[u] = ", ".join(kena)
    if i % 25 == 0:
        print(f"   ...{i}/{len(urls)}")

print(f"\n   halaman yang memuat nomor ({len([v for v in temuan.values() if not v.startswith('GAGAL')])}):")
for u, v in sorted(temuan.items()):
    if not v.startswith("GAGAL"):
        print(f"   {v:<52} {u}")
gagal = [u for u, v in temuan.items() if v.startswith("GAGAL")]
if gagal:
    print(f"\n   gagal diperiksa: {len(gagal)} halaman")
