#!/usr/bin/env python3
"""Verifikasi post 2823 sesudah perbaikan 2026-10-06: baca ulang REST + halaman live."""
import base64, html as htmlmod, json, os, re, sys, urllib.request
sys.path.insert(0, "/home/mantapman/.hermes/profiles/atun/workspace")
from cfg_tslaw import CFG

AUTH = base64.b64encode(f"{CFG['user']}:{CFG['pass']}".encode()).decode()
HDR = {"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0"}
PID = 2823
OUT = "/home/mantapman/.hermes/profiles/atun/workspace/tslaw_pemulihan/perbaikan_20261006"
os.makedirs(OUT, exist_ok=True)

req = urllib.request.Request(f"https://tslaw.id/wp-json/wp/v2/posts/{PID}?context=edit", headers=HDR)
with urllib.request.urlopen(req, timeout=90) as r:
    p = json.load(r)
raw = p["content"]["raw"]
m = p.get("meta") or {}


def wc_audit(s):
    return len(re.sub(r"<[^>]+>", " ", s).split())


def wc_bersih(s):
    t = htmlmod.unescape(re.sub(r"<(script|style).*?</\1>", " ", s, flags=re.S))
    return len(re.sub(r"<[^>]+>", " ", t).split())


seb = open(f"{OUT}/post_{PID}_SEBELUM.html").read()
hasil = {
    "id": p["id"], "slug": p["slug"], "modified": p["modified"], "status": p["status"],
    "judul_h1": p["title"]["raw"],
    "seo_title": m.get("_yoast_wpseo_title"),
    "fokus_kw": m.get("_yoast_wpseo_focuskw"),
    "meta_desc": m.get("_yoast_wpseo_metadesc"),
    "kata_bersih_sebelum": wc_bersih(seb), "kata_bersih_sesudah": wc_bersih(raw),
    "kata_audit_sebelum": wc_audit(seb), "kata_audit_sesudah": wc_audit(raw),
    "h2": len(re.findall(r"<h2", raw)), "h3": len(re.findall(r"<h3", raw)),
    "faq_tampil": len(re.findall(r"<h3>", raw)),
    "schema_question": len(re.findall(r'"@type": "Question"', raw)),
    "schema_faqpage": raw.count('"FAQPage"'),
    "tautan_pilar": raw.count("law-firm-surabaya"),
    "tombol_wa": raw.count("wa.me/6281909222026"),
    "h3_tanpa_skema_di_faq": len(re.findall(r"<h3>", raw)) - len(re.findall(r'"@type": "Question"', raw)),
    "tslaw_sisa": raw.count("TSLaw"),
    "kamu_sisa": len(re.findall(r"\bkamu\b", raw, re.I)),
    "p_kosong": raw.count("<p></p>"),
    "placeholder": re.findall(r"\{[A-Za-z_\[\]0-9]+\}", raw),
}
json.dump(hasil, open(f"{OUT}/post_{PID}_VERIFIKASI.json", "w"), ensure_ascii=False, indent=1)
for k, v in hasil.items():
    print(f"  {k:<24}: {v}")

try:
    rq = urllib.request.Request(f"https://www.tslaw.id/{p['slug']}/?nocache=20261006",
                                headers={"User-Agent": "Mozilla/5.0", "Cache-Control": "no-cache"})
    with urllib.request.urlopen(rq, timeout=90) as r:
        live = r.read().decode(errors="replace")
    t = re.search(r"<title>(.*?)</title>", live, re.S)
    d = re.search(r'<meta name="description" content="(.*?)"', live, re.S)
    h1 = re.search(r"<h1[^>]*>(.*?)</h1>", live, re.S)
    teks = htmlmod.unescape(re.sub(r"<[^>]+>", " ", live))
    print("\n--- live HTML (nocache) ---")
    print("  <title>  :", htmlmod.unescape(t.group(1)).strip() if t else None)
    print("  <h1>     :", htmlmod.unescape(re.sub(r"<[^>]+>", "", h1.group(1))).strip() if h1 else None)
    print("  meta dsc :", (htmlmod.unescape(d.group(1)).strip() if d else None))
    for label, cek in [("H2 tanpa biaya", "Cara Mengurus Kasus Tanah Tanpa Biaya"),
                       ("UU 16/2011", "UU Nomor 16 Tahun 2011"),
                       ("Posbakum", "Posbakum"),
                       ("Pasal 237 HIR", "Pasal 237 HIR"),
                       ("Pasal 22 UU 18/2003", "Pasal 22 UU Nomor 18 Tahun 2003"),
                       ("tautan pilar", "law-firm-surabaya"),
                       ("tombol WA", "wa.me/6281909222026"),
                       ("schema FAQPage", '"FAQPage"'),
                       ("FAQ tampil", "Pertanyaan yang Sering Diajukan")]:
        print(f"  {label:<22}: {cek in live}")
    print("  live kata bersih :", len(re.sub(r"<[^>]+>", " ", re.sub(r"<(script|style).*?</\1>", " ", live, flags=re.S)).split()))
    open(f"{OUT}/live_2823_sesudah.html", "w").write(live)
except Exception as e:
    print("live gagal:", e)
