#!/usr/bin/env python3
"""TSC — daftar layanan/artikel dari WP + nomor WA yang benar-benar dipakai di situs."""
import base64, html, importlib.util, json, re, time, urllib.error, urllib.request

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


def rest(path):
    h = {"Authorization": f"Basic {AUTH}", **UA}
    r = urllib.request.Request(f"https://{DOM}{path}", headers=h)
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=180) as x:
                return json.loads(x.read())
        except urllib.error.HTTPError as e:
            return {"err": e.code}
        except Exception:
            time.sleep(4)
    return {}


print("=== nomor WA yang dipakai di halaman utama ===")
try:
    t = urllib.request.urlopen(urllib.request.Request(f"https://{DOM}/", headers=UA), timeout=90).read().decode("utf-8", "replace")
    wa = sorted(set(re.findall(r"wa\.me/(\d+)", t))) + sorted(set(re.findall(r"api\.whatsapp\.com/send\?phone=(\d+)", t)))
    print("   wa.me:", wa[:6])
    tel = sorted(set(re.findall(r'tel:\+?(\d[\d\-\s]{7,})', t)))[:4]
    print("   tel:", tel)
    print("   alamat:", re.findall(r'(Krian|Sidoarjo|Surabaya)[^<]{0,60}', t)[:3])
except Exception as e:
    print("   gagal:", str(e)[:80])

print("\n=== artikel/layanan TSC (30 terbaru) ===")
d = rest("/wp-json/wp/v2/posts?per_page=30&orderby=date&order=desc&status=publish&_fields=id,slug,title,link")
if isinstance(d, list):
    for p in d:
        print(f"   #{p['id']:>5} | {html.unescape(p['title']['rendered'])[:74]}")
        print(f"           /{p['slug'][:80]}")
else:
    print("   gagal:", str(d)[:100])

print("\n=== halaman (page) TSC ===")
d2 = rest("/wp-json/wp/v2/pages?per_page=40&_fields=id,slug,title")
if isinstance(d2, list):
    for p in d2:
        print(f"   #{p['id']:>5} | {html.unescape(p['title']['rendered'])[:70]} | /{p['slug'][:50]}")
