#!/usr/bin/env python3
"""Lanjutkan pembaruan tautan internal ke slug baru, hanya untuk artikel yang terdampak, dengan jeda.

Jalankan: python3 tsc_lanjut_tautan.py [--go]
"""
import base64, importlib.util, json, os, re, sys, time, urllib.error, urllib.request

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
BACKUP = f"{WS}/tsc_backup_link_slug"
os.makedirs(BACKUP, exist_ok=True)
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)
CFG = m.CFG
DOM = CFG["domain"]
AUTH = base64.b64encode(f"{CFG['user']}:{CFG['pass']}".encode()).decode()
UA = {"User-Agent": "Mozilla/5.0"}
LAMA = json.load(open(f"{WS}/drafts/tsc_slug_lama.json"))
PETA = {}
for x in LAMA:
    PETA[x["slug"]] = None      # slug lama, pasangannya diisi nanti


def rest(path, method="GET", data=None, coba=4):
    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(coba):
        try:
            with urllib.request.urlopen(r, timeout=120) as x:
                return x.status, json.loads(x.read())
        except urllib.error.HTTPError as e:
            if e.code in (429, 404):
                time.sleep(6 * (i + 1))       # situs membatasi → mundur dulu
                continue
            return e.code, e.read().decode()[:200]
        except Exception:
            time.sleep(5)
    return 0, "gagal"


# 1. peta slug lama → slug baru (dengan jeda)
print("mengambil peta slug...", flush=True)
for lama in list(PETA):
    for x in LAMA:
        if x["slug"] != lama:
            continue
        st, o = rest(f"/wp-json/wp/v2/posts/{x['id']}?_fields=id,slug")
        if isinstance(o, dict):
            PETA[lama] = o["slug"]
        time.sleep(0.8)
        break
peta = {k: v for k, v in PETA.items() if v and v != k}
print(f"slug berubah: {len(peta)}", flush=True)

# 2. daftar artikel yang terdampak (dari log percobaan sebelumnya)
ID = []
with open("/tmp/tsc_link_go.txt", errors="replace") as f:
    for baris in f:
        mc = re.match(r"\s+#(\d+)\s+(posts|pages)", baris)
        if mc:
            ID.append(int(mc.group(1)))
ID = sorted(set(ID))
print(f"artikel yang punya tautan lama: {len(ID)}", flush=True)

# 3. perbarui satu per satu dengan jeda
go = "--go" in sys.argv
beres = gagal = 0
for i, pid in enumerate(ID, 1):
    st, o = rest(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=id,content,link")
    if not isinstance(o, dict):
        print(f"  #{pid} ❌ baca gagal ({st})", flush=True)
        gagal += 1
        continue
    raw = o["content"]["raw"]
    baru, n = raw, 0
    for lama, gres in peta.items():
        n += len(re.findall(re.escape(lama), baru))
        baru = baru.replace(lama, gres)
    if not n:
        continue
    if not go:
        print(f"  #{pid} perlu {n} tautan", flush=True)
        continue
    open(f"{BACKUP}/post_{pid}_lanjut.txt", "w").write(raw)
    st2, _ = rest(f"/wp-json/wp/v2/posts/{pid}", "POST", {"content": baru})
    time.sleep(1.5)
    _, cek = rest(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=content")
    masih = sum(len(re.findall(re.escape(l), cek.get("content", {}).get("raw", ""))) for l in peta) \
        if isinstance(cek, dict) else -1
    status = "✅" if st2 == 200 and masih == 0 else "❌"
    print(f"  {status} #{pid} {n} tautan | HTTP {st2} | sisa nama lama: {masih}", flush=True)
    beres += (status == "✅")
    gagal += (status != "✅")
    time.sleep(1.2)

print(f"\nberes: {beres} · gagal: {gagal}")
if not go:
    print("(dry run — pakai --go)")
