#!/usr/bin/env python3
"""Verifikasi akhir TSC: sisa tautan berspasi, nomor yang terpakai, dan sisa merek lama di konten."""
import base64, 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("=== 1. halaman depan (tema + konten) ===")
t = urllib.request.urlopen(urllib.request.Request(f"https://{DOM}/", headers=UA), timeout=90).read().decode("utf-8", "replace")
for m2 in re.finditer(r'href="([^"]*(?:wa\.me|api\.whatsapp)[^"]*)"', t):
    h = m2.group(1).replace("&#038;", "&")
    tanda = " ⚠ masih ada spasi" if re.search(r"phone=(%20|\+| )", h) else ""
    print(f"   {h[:80]}{tanda}")

print("\n=== 2. sisa merek lama di konten (posts + pages) ===")
tot = {"Klinik DNI": 0, "klinikdnisidoarjo.com": 0, "klinikdnikrian.com": 0, "0812-XXXX": 0}
contoh = []
for jenis in ("posts", "pages"):
    page = 1
    while True:
        d = rest(f"/wp-json/wp/v2/{jenis}?per_page=100&page={page}&status=publish&context=edit"
                 f"&_fields=id,slug,link,title,content")
        if not isinstance(d, list) or not d:
            break
        for x in d:
            raw = x["content"]["raw"]
            kena = {k: len(re.findall(k, raw, re.I)) for k in tot}
            if any(kena.values()):
                for k, v in kena.items():
                    tot[k] += v
                if len(contoh) < 8:
                    contoh.append((x["link"], {k: v for k, v in kena.items() if v}))
        if len(d) < 100:
            break
        page += 1

for k, v in tot.items():
    print(f"   {k:<22} {v} kemunculan")
print("\n   contoh halaman:")
for link, kena in contoh:
    print(f"     {link[:74]} → {kena}")
