#!/usr/bin/env python3
"""Verifikasi halaman hidup: pastikan tidak ada lagi kalimat yang patah di tengah."""
import base64, importlib.util, json, re, time, urllib.request

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg", f"{WS}/cfg_tsc.py")
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
A = base64.b64encode(f"{m.CFG['user']}:{m.CFG['pass']}".encode()).decode()
H = {"Authorization": f"Basic {A}", "User-Agent": "Mozilla/5.0"}
UA = {"User-Agent": "Mozilla/5.0"}


def patahan_hidup(html):
    n = 0
    contoh = []
    for mo in re.finditer(r"<(p|li|h2|h3)(?:\s[^>]*)?>(.*?)</\1>", html, re.S | re.I):
        dalam = mo.group(2)
        if "<br" not in dalam:
            continue
        for bagian in re.split(r"<br\s*/?>", dalam)[:-1]:
            b = re.sub("<[^>]+>", "", bagian).strip()
            if b and not re.search(r"[.!?:;]$", b):
                n += 1
                if len(contoh) < 2:
                    contoh.append(b[-70:])
    return n, contoh


for pid in (1738, 1731, 9102, 10134):
    x = json.loads(urllib.request.urlopen(urllib.request.Request(
        f"https://www.theskincodeclinic.com/wp-json/wp/v2/posts/{pid}?context=edit&_fields=link", headers=H),
        timeout=90).read())
    u = x["link"] + f"?cek={int(time.time())}"
    t = urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=90).read().decode("utf-8", "replace")
    n, contoh = patahan_hidup(t)
    print(f"   #{pid} patahan di halaman hidup: {n} · {x['link'].replace('https://www.theskincodeclinic.com', '')}")
    for c in contoh:
        print(f"        …{c}")
    time.sleep(1)
