#!/usr/bin/env python3
"""Rapikan baris yang terpotong di tengah kalimat pada draf klaster rumah sakit StudioSoft.

Atribut tag dipertahankan, teks tidak diubah. Ada cadangan isi asli.
"""
import base64, json, re, urllib.request

AUTH = base64.b64encode(b"bambangbot:q26r RePo BVy6 pwU2 F3z7 ouyl").decode()
H = {"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0", "Content-Type": "application/json"}
TAG = ("p", "li", "h1", "h2", "h3", "h4", "blockquote", "figcaption")
POLA = re.compile(r"(<(" + "|".join(TAG) + r")(?:\s[^>]*)?>)(.*?)</\2>", re.S | re.I)


def rapikan(isi):
    def ganti(mo):
        dalam = mo.group(3)
        if "<br" in dalam or "\n" not in dalam:
            return mo.group(0)
        rapi = re.sub(r"\s{2,}", " ", re.sub(r"\s*\n\s*", " ", dalam)).strip()
        return f"{mo.group(1)}{rapi}</{mo.group(2)}>"
    return POLA.sub(ganti, isi)


cadangan = {}
for pid in (9406, 9409, 9412, 9415, 9418):
    for _ in range(3):
        try:
            x = json.loads(urllib.request.urlopen(urllib.request.Request(
                f"https://studiosoft.id/wp-json/wp/v2/posts/{pid}?context=edit&_fields=content,slug",
                headers=H), timeout=180).read())
            break
        except Exception as e:
            print(f"   #{pid} baca gagal, ulangi: {str(e)[:50]}")
    isi = x["content"]["raw"]
    rapi = rapikan(isi)
    t1 = re.sub(r"\s+", " ", re.sub("<[^>]+>", " ", isi)).strip()
    t2 = re.sub(r"\s+", " ", re.sub("<[^>]+>", " ", rapi)).strip()
    sisa = 0
    for mo in re.finditer(r"<(p|li|h2|h3)[^>]*>(.*?)</\1>", rapi, re.S):
        b = mo.group(2)
        if "\n" not in b:
            continue
        for t3 in [q.strip() for q in b.split("\n")][:-1]:
            if t3 and not re.search(r"[.!?:;]$", t3):
                sisa += 1
    print(f"   #{pid} {x['slug'][:44]:<46} teks {'sama' if t1 == t2 else '⚠ BERUBAH'} · patahan sisa {sisa}")
    if t1 == t2 and isi != rapi:
        cadangan[str(pid)] = isi
        r = urllib.request.Request(f"https://studiosoft.id/wp-json/wp/v2/posts/{pid}",
                                   data=json.dumps({"content": rapi}).encode(), headers=H, method="POST")
        urllib.request.urlopen(r, timeout=180).read()

json.dump(cadangan, open("/home/mantapman/.hermes/profiles/atun/workspace/ss_backup_klaster_rs.json", "w"),
          ensure_ascii=False)
print(f"\n✅ {len(cadangan)} draf dirapikan · cadangan: ss_backup_klaster_rs.json")
