#!/usr/bin/env python3
"""TSLaw: verifikasi akhir — tombol WhatsApp, skema FAQ, dan tampilan live."""
import base64, html, json, re, time, urllib.request, importlib.util

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg_tslaw", f"{WS}/cfg_tslaw.py")
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
DOM, AUTH = "www.tslaw.id", base64.b64encode(f'{m.CFG["user"]}:{m.CFG["pass"]}'.encode()).decode()
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124.0 Safari/537.36"}


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


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

tanpa_wa = [p["id"] for p in posts if not re.search(r"wa\.me|whatsapp", p["content"]["raw"] or "", re.I)]
ada_faq = [p["id"] for p in posts if "FAQPage" in (p["content"]["raw"] or "")]
print(f"=== ringkasan isi {len(posts)} artikel ===")
print(f"   artikel tanpa tombol WhatsApp : {len(tanpa_wa)} {tanpa_wa[:8]}")
print(f"   artikel dengan skema FAQPage  : {len(ada_faq)}")
print(f"   artikel ber-FAQ tanpa skema   : {len(posts) - len(ada_faq)} (bagian FAQ belum terdeteksi otomatis)")

print("\n=== uji tampilan live (3 artikel) ===")
for p in [x for x in posts if x["id"] in (3356, 3232, 3065)]:
    u = f"https://{DOM}/{p['slug']}/"
    try:
        h = urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=120).read().decode("utf-8", "replace")
        tombol = len(re.findall(r'href="https://wa\.me/6281909222026', h))
        skema = h.count("application/ld+json")
        faqpage = "FAQPage" in h
        # apakah JSON-LD muncul sebagai teks terlihat?
        teks_mentah = "@context" in re.sub(r'<script(?![^>]*application/ld\+json).*?</script>', "", h, flags=re.S)
        print(f"\n   /{p['slug'][:50]}")
        print(f"      tombol WA: {tombol} | blok skema: {skema} | FAQPage: {faqpage}")
        print(f"      skema tampil sebagai teks: {'YA — perlu dibersihkan' if teks_mentah else 'tidak ✅'}")
    except Exception as e:
        print(f"   /{p['slug'][:40]}: gagal {str(e)[:60]}")
