#!/usr/bin/env python3
"""Perbaiki tautan .htm yang sekarang 404 di draft #3717 dan #3722 (permukaLan: permalink sudah kembali ke /%postname%/).
Salinan isi lama disimpan dulu; isi baru diuji ulang 200 sebelum dikirim."""
import base64, json, os, re, urllib.request, urllib.error, time

DOM = "tslaw.id"
USER, PASS = "bambangbot", "EFKm EYGx VQCP Y9go ncPr uM2Y"
AUTH = base64.b64encode(f"{USER}:{PASS}".encode()).decode()
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36"}
OUT = "/home/mantapman/.hermes/profiles/atun/workspace/tslaw_listikel"
os.makedirs(OUT, exist_ok=True)


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 i in range(4):
        try:
            with urllib.request.urlopen(r, timeout=180) as x:
                return x.status, json.loads(x.read())
        except urllib.error.HTTPError as e:
            return e.code, e.read().decode()[:200]
        except Exception as e:
            print("   (ulang)", str(e)[:50]); time.sleep(6)
    return 0, "gagal"


def head(u):
    try:
        with urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=45) as x:
            return x.status
    except urllib.error.HTTPError as e:
        return e.code
    except Exception as e:
        return f"ERR {str(e)[:40]}"


for pid in (3717, 3722):
    st, p = rest(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=id,slug,content")
    raw = p["content"]["raw"]
    open(f"{OUT}/salinan_{pid}_sebelum.webp.txt", "w").write(raw)
    baru = raw
    n = 0
    for u in sorted(set(re.findall(r'href="(https://www\.tslaw\.id/[^"]*\.htm)"', raw))):
        tujuan = u[:-4] + "/"
        kode = head(tujuan)
        print(f"  #{pid} {u}\n      -> {tujuan}  [{kode}]")
        if kode == 200:
            baru = baru.replace(u, tujuan); n += 1
        else:
            print(f"      LEWATI (tujuan bukan 200)")
    sisa = re.findall(r'href="(https://www\.tslaw\.id/[^"]*\.htm)"', baru)
    print(f"  #{pid}: {n} tautan diganti; sisa .htm = {len(sisa)}")
    if n and not sisa:
        st, r = rest(f"/wp-json/wp/v2/posts/{pid}", "POST", {"content": baru})
        print(f"  #{pid}: PUT -> HTTP {st} (status {r.get('status') if isinstance(r, dict) else r})")
        time.sleep(2)
        st, c = rest(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=content")
        sisa2 = re.findall(r'href="(https://www\.tslaw\.id/[^"]*\.htm)"', c["content"]["raw"])
        print(f"  #{pid}: baca ulang -> sisa .htm = {len(sisa2)}  ({'BERSIH' if not sisa2 else sisa2})")
    time.sleep(2)
