#!/usr/bin/env python3
"""Uji: apakah <script ld+json> di konten post LEIT selamat & tampil di HTML publik?"""
import base64, json, re, urllib.request

SITE = "https://www.leitsurabaya.com"
AUTH = base64.b64encode(b"bambangbot:zibd dLIV xY8x onP9 39qL hiNr").decode()
PID = 3825
UJI = ('<script type="application/ld+json">{"@context":"https://schema.org","@type":"FAQPage",'
       '"mainEntity":[{"@type":"Question","name":"Uji coba skema LEIT?","acceptedAnswer":'
       '{"@type":"Answer","text":"Ini uji coba, akan dihapus."}}]}</script>')


def api(path, data=None, method="GET"):
    h = {"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0"}
    body = None
    if data is not None:
        body = json.dumps(data).encode()
        h["Content-Type"] = "application/json"
    r = urllib.request.Request(SITE + path, data=body, headers=h, method=method)
    with urllib.request.urlopen(r, timeout=240) as x:
        return json.loads(x.read())


raw = api(f"/wp-json/wp/v2/posts/{PID}?context=edit&_fields=content")["content"]["raw"]
if "Uji coba skema LEIT" in raw:
    print("uji sudah pernah dipasang — bersihkan dulu")
else:
    st = api(f"/wp-json/wp/v2/posts/{PID}", {"content": raw + "\n" + UJI}, "POST")
    print("POST status (id tersimpan):", st.get("id"))

r = urllib.request.Request(SITE + "/kursus-bahasa-inggris-paling-terjangkau-surabaya/",
                           headers={"User-Agent": "Mozilla/5.0", "Cache-Control": "no-cache"})
html = urllib.request.urlopen(r, timeout=90).read().decode("utf-8", "replace")
print("script ld+json di HTML publik:", "DITEMUKAN" if "Uji coba skema LEIT" in html else "TIDAK (dibersihkan WP)")
print("jumlah blok ld+json:", len(re.findall(r'application/ld\+json', html)))
