#!/usr/bin/env python3
"""Ambil isi mentah post 3179 + 3205 (banding kembar) dan simpan backup."""
import base64, json, re, sys, time, urllib.request, importlib.util, os, difflib

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
DIR = f"{WS}/tslaw_pemulihan/perbaikan_20261012"
os.makedirs(DIR, exist_ok=True)
spec = importlib.util.spec_from_file_location("cfg_tslaw", f"{WS}/cfg_tslaw.py")
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
AUTH = base64.b64encode(f'{m.CFG["user"]}:{m.CFG["pass"]}'.encode()).decode()
UA = {"User-Agent": "Mozilla/5.0"}


def rest(p, data=None, method=None):
    r = urllib.request.Request(f"https://www.tslaw.id{p}",
                              headers={"Authorization": f"Basic {AUTH}", "Content-Type": "application/json", **UA},
                              data=json.dumps(data).encode() if data else None, method=method)
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=180) as x:
                return json.loads(x.read())
        except urllib.error.HTTPError as e:
            return {"__http_error": e.code, "body": e.read().decode()[:400]}
        except Exception as e:
            print("  retry:", e); time.sleep(4)
    return {}


def bersih(raw):
    """Buang blok script/style, sisakan teks paragraf."""
    t = re.sub(r"<script.*?</script>", " ", raw, flags=re.S | re.I)
    t = re.sub(r"<style.*?</style>", " ", t, flags=re.S | re.I)
    t = re.sub(r"<!--.*?-->", " ", t, flags=re.S)
    t = re.sub(r"<[^>]+>", " ", t)
    t = re.sub(r"&nbsp;", " ", t)
    return re.sub(r"\s+", " ", t).strip()


for pid in [int(x) for x in sys.argv[1:]]:
    d = rest(f"/wp-json/wp/v2/posts/{pid}?context=edit")
    if not isinstance(d, dict) or "id" not in d:
        print(f"#{pid} GAGAL", str(d)[:200]); continue
    raw = d["content"]["raw"] or ""
    open(f"{DIR}/post_{pid}_SEBELUM.json", "w").write(json.dumps(d, ensure_ascii=False, indent=1))
    open(f"{DIR}/post_{pid}_SEBELUM.html", "w").write(raw)
    print(f"#{pid} /{d['slug']} raw={len(raw)} audit_kata={len(bersih(raw).split())} modified={d['modified']}")
    print("   judul:", d["title"]["raw"])
    print("   jenis:", d.get("type"), "status:", d.get("status"))
    # struktur
    for tag in ["h2", "h3"]:
        for x in re.findall(rf"<{tag}[^>]*>(.*?)</{tag}>", raw, re.S):
            print(f"   {tag.upper()}: {re.sub(r'<[^>]+>', '', x).strip()[:95]}")
    print("   tombol WA:", re.findall(r"wa\.me/[0-9]+", raw))
    print("   tautan internal:", sorted(set(re.findall(r"tslaw\.id/([a-z0-9\-\.]+)", raw)))[:12])
print("->", DIR)
