#!/usr/bin/env python3
"""Verifikasi post 2940: baca ulang dari 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 = 2940
OUT = "/home/mantapman/.hermes/profiles/atun/workspace/tslaw_pemulihan/perbaikan_20261005"
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):   # metode skrip audit (script tag tidak dibuang)
    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())

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": wc_bersih(raw),
    "kata_audit": wc_audit(raw),
    "jumlah_h2": len(re.findall(r"<h2", raw)),
    "faq_tampil": len(re.findall(r"<h3>", raw)),
    "schema_question": len(re.findall(r'"@type": "Question"', raw)),
    "tautan_pilar": raw.count("law-firm-surabaya"),
    "tombol_wa": raw.count("wa.me/6281909222026"),
    "tslaw_sisa": raw.count("TSLaw"),
    "tito_sisa": raw.count("Tito Supriyanto"),
    "p_bersarang": re.findall(r"<p>[^<]*<p>", raw),
    "placeholder": re.findall(r"\{[A-Za-z_\[\\\]0-9]+\}", raw),
}
# sebelum (dari cadangan)
seb = open(f"{OUT}/post_{PID}_SEBELUM.html").read()
hasil["kata_audit_sebelum"] = wc_audit(seb)
hasil["kata_bersih_sebelum"] = wc_bersih(seb)
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:<22}: {v}")

try:
    rq = urllib.request.Request(f"https://www.tslaw.id/{p['slug']}/",
                                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)
    print("\n--- live HTML ---")
    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))
    print("  H2 baru ada  :", "Surat Kuasa Mutlak" in live)
    print("  tautan pilar :", "law-firm-surabaya" in live)
    print("  tombol WA    :", "wa.me/6281909222026" in live)
    print("  schema FAQ   :", '"FAQPage"' in live)
    open(f"{OUT}/live_2940_sesudah.html", "w").write(live)
except Exception as e:
    print("live gagal:", e)
