#!/usr/bin/env python3
"""Verifikasi #2908 setelah tulis: baca ulang REST (?context=edit), bandingkan isi/judul/slug/meta,
lalu periksa halaman publik dengan cache buster."""
import base64, html as H, json, re, time, urllib.request, urllib.error

DIR = "/home/mantapman/.hermes/profiles/atun/workspace/tslaw_pemulihan/perbaikan_20261019"
DOM = "tslaw.id"
AUTH = base64.b64encode(b"bambangbot:EFKm EYGx VQCP Y9go ncPr uM2Y").decode()
PID = 2908
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36"}

kirim = open(f"{DIR}/post_{PID}_SESUDAH.html").read()
sebelum = json.load(open(f"{DIR}/post_{PID}_SEBELUM.json"))

h = {"Authorization": f"Basic {AUTH}", **UA}
req = urllib.request.Request(f"https://{DOM}/wp-json/wp/v2/posts/{PID}?context=edit", headers=h)
with urllib.request.urlopen(req, timeout=120) as x:
    p = json.loads(x.read())
json.dump(p, open(f"{DIR}/post_{PID}_VERIFIKASI.json", "w"), ensure_ascii=False, indent=1)

raw = p["content"]["raw"]
print("isi identik dengan yang dikirim:", raw == kirim)
print("judul tetap:", p["title"]["raw"] == sebelum["title"]["raw"], "|", p["title"]["raw"])
print("slug tetap:", p["slug"] == sebelum["slug"], "|", p["slug"])
mb, ma = sebelum.get("meta") or {}, p.get("meta") or {}
for k in ("_yoast_wpseo_focuskw", "_yoast_wpseo_metadesc"):
    print(f"{k} tetap:", mb.get(k) == ma.get(k), "|", ma.get(k))
print("status:", p["status"])


def kata(s):
    t = re.sub(r"<(script|style)[^>]*>.*?</\1>", " ", s, flags=re.S | re.I)
    t = re.sub(r"<[^>]+>", " ", t)
    t = re.sub(r"&[a-z]+;", " ", t)
    return len(re.findall(r"[A-Za-z0-9][A-Za-z0-9'\-]*", t))


print("kata (REST):", kata(raw))

# ---- halaman publik
url = f"{p['link']}?nocache={int(time.time())}"
with urllib.request.urlopen(urllib.request.Request(url, headers=UA), timeout=120) as x:
    live = x.read().decode("utf-8", "replace")
    print("\nhalaman publik HTTP", x.status, url)
open(f"{DIR}/post_{PID}_SESUDAH_LIVE.html", "w").write(live)

isi = live
for s in ["Status SIUP dan TDP Setelah OSS Berbasis Risiko", "Izin dan Sertifikat Sektoral",
          "Cek Cepat: Lima Dokumen yang Wajib Ada", "Kapan Sebaiknya Melibatkan Advokat",
          "Kesalahan yang Paling Sering Terjadi"]:
    print("  H2 tampil:", s, "->", s in isi)
print("  tombol WA tampil:", "wa.me/6281909222026" in isi)
print("  tautan pilar tampil:", "/law-firm-surabaya/" in isi)

# skema FAQPage
items = []
for m in re.finditer(r'<script[^>]*application/ld\+json[^>]*>(.*?)</script>', isi, re.S):
    try:
        d = json.loads(H.unescape(m.group(1)).strip())
    except Exception as e:
        print("  skema gagal parse:", str(e)[:60])
        continue
    for node in (d if isinstance(d, list) else [d]):
        if isinstance(node, dict) and node.get("@type") == "FAQPage":
            items = node.get("mainEntity", [])
print("  skema FAQPage item:", len(items), "valid json:", bool(items))
tampil = re.findall(r"<h3[^>]*>(.*?)</h3>", isi, re.S)
tampil = [re.sub(r"<[^>]+>", "", t).strip() for t in tampil]
print("  FAQ tampil di halaman:", len(tampil))
for it in items:
    q = it["name"]
    print("   -", q, "| ada di halaman:", q in tampil)
print("  jumlah cocok:", sum(1 for it in items if it["name"] in tampil))

# tautan badan artikel
bad = []
for u in sorted(set(re.findall(r'https://www\.tslaw\.id/[^"\'\s<]+', raw))):
    try:
        with urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=60) as x:
            st = x.status
    except urllib.error.HTTPError as e:
        st = e.code
    except Exception:
        st = 0
    if st != 200:
        bad.append((st, u))
print("  tautan mati:", bad)
print("  em dash di isi:", raw.count("\u2014"), "| paragraf bersarang:", raw.count("<p><p>"))
