#!/usr/bin/env python3
"""Verifikasi #3175 setelah tulis: REST baca ulang, judul/slug/meta tetap, halaman publik."""
import base64, json, re, time, urllib.request, urllib.error

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


def rest(path):
    h = {"Authorization": f"Basic {AUTH}", **UA}
    r = urllib.request.Request(f"https://{DOM}{path}", headers=h)
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=120) as x:
                return json.load(x)
        except Exception:
            time.sleep(3)


asli = json.load(open(f"{DIR}/post_3175_SEBELUM.json"))
dikirim = open(f"{DIR}/post_3175_SESUDAH_dryrun.html").read()
st, p = None, rest(f"/wp-json/wp/v2/posts/{POST_ID}?context=edit&_fields=id,slug,link,title,content,meta,modified")

raw = p["content"]["raw"]
hasil = {
    "content_identik": raw == dikirim,
    "judul_tetap": p["title"]["rendered"].strip() == asli["title"]["rendered"].strip(),
    "slug_tetap": p["slug"] == asli["slug"],
    "fokus_tetap": (p["meta"].get("_yoast_wpseo_focuskw") == asli["meta"].get("_yoast_wpseo_focuskw")),
    "metadesc_tetap": (p["meta"].get("_yoast_wpseo_metadesc") == asli["meta"].get("_yoast_wpseo_metadesc")),
    "panjang_raw": len(raw),
    "modified": p.get("modified"),
}
print("== REST baca ulang")
for k, v in hasil.items():
    print(f"   {k}: {v}")
if not hasil["content_identik"]:
    a, b = dikirim, raw
    i = next((i for i in range(min(len(a), len(b))) if a[i] != b[i]), min(len(a), len(b)))
    print("   beda di posisi", i, repr(a[max(0, i-80):i+80]), "||", repr(b[max(0, i-80):i+80]))

print("\n== halaman publik")
url = p["link"] + f"?nocache={int(time.time())}"
with urllib.request.urlopen(urllib.request.Request(url, headers=UA), timeout=120) as x:
    kode, html = x.status, x.read().decode("utf-8", "replace")
print("   HTTP", kode, "| panjang", len(html))
open(f"{DIR}/post_3175_SESUDAH_LIVE.html", "w").write(html)

H2BARU = ["Apa Saja yang Termasuk HKI?", "Jenis Kekayaan Intelektual yang Relevan untuk UMKM",
          "Mengapa UMKM Harus Daftarkan HKI?", "Proses Pendaftaran Merek",
          "Konsekuensi Jika HKI Tidak Didaftarkan", "Risiko yang Sering Terjadi",
          "Langkah Praktis Melindungi Aset", "Kesalahan yang Sering Terjadi Saat Mendaftarkan Merek",
          "Kapan Sebaiknya Melibatkan Advokat", "Kesimpulan"]
for h in H2BARU:
    print(f"   H2 tampil [{h}]:", h.replace("&", "&amp;") in html or h in html)

# skema FAQPage di halaman
skema = re.findall(r'<script type="application/ld\+json"[^>]*>(.*?)</script>', html, re.S)
faq = None
for s in skema:
    try:
        d = json.loads(s)
    except Exception:
        continue
    kandidat = d if isinstance(d, list) else [d]
    for k in kandidat:
        if isinstance(k, dict) and k.get("@type") == "FAQPage":
            faq = k
if faq:
    graf = faq.get("mainEntity", [])
    tampil = re.findall(r"<h3>(.*?)</h3>", html)
    tampil_bersih = [re.sub(r"<[^>]+>", "", t).strip() for t in tampil]
    cocok = [q["name"] for q in graf if q["name"] in tampil_bersih]
    print(f"   skema FAQPage: VALID, {len(graf)} item | FAQ tampil: {len(tampil_bersih)} | cocok: {len(cocok)}/{len(graf)}")
else:
    print("   skema FAQPage: TIDAK ADA")

# tombol WA, tautan pilar, tautan mati
print("   tombol WA:", "wa.me/6281909222026" in html, "| tautan pilar:", "law-firm-surabaya" in html)
isi = html.split('<div class="entry-content', 1)[-1]
tautan = set(re.findall(r'href="(https://www\.tslaw\.id/[^"#]*)"', isi))
mati = []
for u in sorted(tautan):
    try:
        with urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=45) as r:
            if r.status != 200:
                mati.append((u, r.status))
    except urllib.error.HTTPError as e:
        mati.append((u, e.code))
    except Exception as e:
        mati.append((u, str(e)[:40]))
print(f"   tautan internal: {len(tautan)} | mati: {len(mati)}", mati)

json.dump({"rest": hasil, "http": kode, "tautan": len(tautan), "mati": mati,
           "skema_item": len(faq.get("mainEntity", [])) if faq else 0},
          open(f"{DIR}/post_3175_VERIFIKASI.json", "w"), ensure_ascii=False, indent=1)
