#!/usr/bin/env python3
"""Cari nomor WhatsApp di seluruh halaman TSC dengan beberapa utas sekaligus (lebih cepat)."""
import re, sys
from concurrent.futures import ThreadPoolExecutor
import urllib.request

UA = {"User-Agent": "Mozilla/5.0 (compatible; AtunBot/1.0)"}
DOM = "theskincodeclinic.com"
NOMOR = sys.argv[1:] or ["6281335114324", "6285117444417"]


def ambil(u):
    try:
        t = urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=25).read().decode("utf-8", "replace")
        return u, sorted({n for n in NOMOR if n in t}), None
    except Exception as e:
        return u, [], str(e)[:40]


sm = urllib.request.urlopen(urllib.request.Request(f"https://www.{DOM}/sitemap_index.xml", headers=UA),
                            timeout=60).read().decode("utf-8", "replace")
sub = re.findall(r"<loc>([^<]+)</loc>", sm)
urls = []
for s in sub:
    try:
        x = urllib.request.urlopen(urllib.request.Request(s, headers=UA), timeout=60).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 diperiksa dengan 10 utas", flush=True)

hasil, gagal = [], 0
with ThreadPoolExecutor(max_workers=10) as ex:
    for i, (u, kena, err) in enumerate(ex.map(ambil, urls), 1):
        if err:
            gagal += 1
        elif kena:
            hasil.append((u, kena))
        if i % 100 == 0:
            print(f"  ...{i}/{len(urls)} (temuan {len(hasil)}, gagal {gagal})", flush=True)

print(f"\n=== halaman yang memuat nomor: {len(hasil)} · gagal dibuka: {gagal} ===")
for u, kena in sorted(hasil, key=lambda x: (x[1], x[0])):
    print(f"  {', '.join(kena):<34} {u}")
