#!/usr/bin/env python3
"""Perbarui slug arsip tag TSC ke nama baru (nama sudah diganti lebih dulu), lalu uji pengalihannya.

#218 «DNI Krian» dihapus karena semakna dengan #99 (keduanya ke The Skin Code Clinic).

Pakai --go untuk menjalankan.
"""
import base64, importlib.util, json, re, sys, time, urllib.error, 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)
CFG = m.CFG
DOM = CFG["domain"]
AUTH = base64.b64encode(f"{CFG['user']}:{CFG['pass']}".encode()).decode()
UA = {"User-Agent": "Mozilla/5.0"}

RENCANA = [
    (99, "the-skin-code-clinic"),
    (88, "the-skin-code-clinic-krian"),
    (471, "the-skin-code-clinic-krian-sidoarjo"),
    (154, "the-skin-code-clinic-sidoarjo"),
    (416, "spesialis-kandungan-the-skin-code-clinic"),
    (436, "dokter-kulit-dan-kelamin-the-skin-code-clinic-krian"),
]
HAPUS = [218]


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=90) as x:
                return x.status, json.loads(x.read())
        except urllib.error.HTTPError as e:
            if e.code in (429, 404):
                time.sleep(5 * (i + 1))
                continue
            return e.code, e.read().decode()[:200]
        except Exception:
            time.sleep(4)
    return 0, "gagal"


class TanpaAlih(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *a, **k):
        return None


OP = urllib.request.build_opener(TanpaAlih)


def cek(url):
    try:
        with OP.open(urllib.request.Request(url, headers=UA), timeout=45) as x:
            return x.status, ""
    except urllib.error.HTTPError as e:
        return e.code, e.headers.get("Location", "")
    except Exception as e:
        return "GAGAL", str(e)[:40]


go = "--go" in sys.argv
for tid, slug_baru in RENCANA:
    st, t = rest(f"/wp-json/wp/v2/tags/{tid}?_fields=id,name,slug,count,link")
    if not isinstance(t, dict):
        print(f"  #{tid} gagal dibaca ({st})")
        continue
    lama = t["link"]
    print(f"  #{tid} «{t['name'][:44]}» · {t.get('count')} artikel")
    print(f"     slug: {t['slug']} → {slug_baru}")
    if go:
        st2, d = rest(f"/wp-json/wp/v2/tags/{tid}", "POST", {"slug": slug_baru})
        time.sleep(2)
        st_lama, loc = cek(lama)
        print(f"     HTTP {st2} · slug sekarang {(d or {}).get('slug') if isinstance(d, dict) else '?'}")
        print(f"     URL lama: {st_lama} → {loc[:70] or '(tanpa tujuan)'}")
    time.sleep(1.2)

for tid in HAPUS:
    st, t = rest(f"/wp-json/wp/v2/tags/{tid}?_fields=id,name,slug,count,link")
    if not isinstance(t, dict):
        continue
    print(f"  hapus #{tid} «{t['name'][:40]}» ({t.get('count')} artikel) → ", end="", flush=True)
    if go:
        st2, _ = rest(f"/wp-json/wp/v2/tags/{tid}?force=true", "DELETE")
        print(f"HTTP {st2}")
    else:
        print("(dry run)")
    time.sleep(1)

if not go:
    print("\n(dry run — pakai --go)")
