#!/usr/bin/env python3
"""Periksa jenis perubahan 'rapikan baris' pada artikel lama: apakah hanya spasi, atau ada teks hilang."""
import base64, importlib.util, difflib, json, re, 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"}
S = "https://www.theskincodeclinic.com"
TAG = ("p", "li", "h1", "h2", "h3", "h4", "blockquote", "figcaption", "td", "th", "strong", "em")


def rapikan(isi):
    def ganti(mo):
        buka, dalam = mo.group(1), mo.group(3)
        if "<br" in dalam:
            return mo.group(0)
        rapi = re.sub(r"\s*\n\s*", " ", dalam)
        rapi = re.sub(r"\s{2,}", " ", rapi).strip()
        return f"{buka}>{rapi}</{mo.group(2)}>"
    pola = re.compile(r"(<(" + "|".join(TAG) + r")(?:\s[^>]*)?>)(.*?)</\2>", re.S | re.I)
    return pola.sub(ganti, isi)


for pid in (1601, 1578, 10274):
    x = json.loads(urllib.request.urlopen(urllib.request.Request(
        f"{S}/wp-json/wp/v2/posts/{pid}?context=edit&_fields=content,link", headers=H), timeout=120).read())
    c = x["content"]["raw"]
    rapi = rapikan(c)
    # bandingkan teks saja (tanpa tag) supaya tahu ada teks yang hilang atau tidak
    t1 = re.sub(r"\s+", " ", re.sub("<[^>]+>", " ", c)).strip()
    t2 = re.sub(r"\s+", " ", re.sub("<[^>]+>", " ", rapi)).strip()
    print(f"\n#{pid} {x['link'].replace(S, '')}")
    print(f"   teks sebelum: {len(t1)} char · sesudah: {len(t2)} char · selisih teks: {len(t1)-len(t2)}")
    if t1 != t2:
        for i, s in enumerate(difflib.unified_diff(t1.split(), t2.split(), lineterm="", n=3)):
            if i > 12:
                break
            print(f"      {s[:110]}")
    else:
        print("   teks identik (hanya baris/spasi yang dirapikan)")
    beda = [l for l in difflib.unified_diff(c.splitlines(), rapi.splitlines(), lineterm="", n=0)]
    print(f"   baris yang berubah: {len(beda)}")
    for b in beda[:6]:
        print(f"      {b[:120]}")
