#!/usr/bin/env python3
"""Ambil post 3175 apa adanya (raw) untuk perbaikan 20 Okt."""
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"


def rest(path, method="GET", data=None):
    h = {"Authorization": f"Basic {AUTH}", **UA}
    body = None
    if data is not None:
        body = json.dumps(data).encode()
        h["Content-Type"] = "application/json"
    r = urllib.request.Request(f"https://{DOM}{path}", data=body, headers=h, method=method)
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=120) as x:
                return x.status, json.loads(x.read())
        except urllib.error.HTTPError as e:
            return e.code, e.read().decode()[:500]
        except Exception:
            time.sleep(3)
    return 0, "gagal"


st, p = rest("/wp-json/wp/v2/posts/3175?context=edit&_fields=id,slug,link,title,status,content,meta,date")
print("status", st)
json.dump(p, open(f"{DIR}/post_3175_SEBELUM.json", "w"), ensure_ascii=False, indent=1)
c = p["content"]["raw"]
open(f"{DIR}/post_3175_SEBELUM.html", "w").write(c)


def kata(html):
    t = re.sub(r"<(script|style)[^>]*>.*?</\1>", " ", html, 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("judul:", p["title"]["rendered"])
print("slug:", p["slug"], "| link:", p["link"])
print("kata:", kata(c), "| em:", c.count("\u2014"), "| wa:", bool(re.search(r"wa\.me/\d+", c)))
print("pilar:", "law-firm-surabaya" in c, "| faqskema:", "FAQPage" in c)
m = p.get("meta") or {}
print("fokus:", m.get("_yoast_wpseo_focuskw"), "| desc:", m.get("_yoast_wpseo_metadesc"))
print("H2:", len(re.findall(r"<h2", c)), "H3:", len(re.findall(r"<h3", c)), "li:", len(re.findall(r"<li", c)))
print("---- isi mentah ----")
print(c)
