#!/usr/bin/env python3
"""TSC — ubah slug artikel yang masih memuat nama lama, lalu cek apakah WordPress mengalihkan URL lama.

Pakai: python3 tsc_ganti_slug.py --test          → uji satu artikel (#1735) lalu hentikan
       python3 tsc_ganti_slug.py --go            → kerjakan semuanya (kecuali yang sudah berubah)
       python3 tsc_ganti_slug.py --cek           → hanya cek pengalihan beberapa URL lama
"""
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"}
daftar = json.load(open(f"{WS}/drafts/tsc_slug_lama.json"))


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


def usul(s):
    s2 = re.sub(r"di-klinik-dni-krian", "di-the-skin-code-clinic", s, flags=re.I)
    s2 = re.sub(r"klinik-dni-krian", "the-skin-code-clinic", s2, flags=re.I)
    s2 = re.sub(r"klinik-dni-sidoarjo", "the-skin-code-clinic-sidoarjo", s2, flags=re.I)
    s2 = re.sub(r"klinik-dni", "the-skin-code-clinic", s2, flags=re.I)
    return re.sub(r"-{2,}", "-", s2).strip("-")


class TanpaAlih(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None          # jangan ikuti pengalihan, supaya status aslinya terlihat


_opener = urllib.request.build_opener(TanpaAlih)


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


if "--cek" in sys.argv:
    for x in daftar[:5]:
        st, tujuan = cek(x["link"])
        print(f"  {st} → {tujuan[:88]}")
    sys.exit(0)

target = [x for x in daftar if x["id"] == 1735] if "--test" in sys.argv else \
         (daftar if "--go" in sys.argv else [])

if not target:
    print("pilih: --test (satu artikel) atau --go (semua) atau --cek")
    sys.exit(0)

for x in target:
    baru = usul(x["slug"])
    if baru == x["slug"]:
        print(f"  #{x['id']} slug tidak berubah, dilewati")
        continue
    print(f"\n  #{x['id']} {x['slug']}")
    print(f"    → {baru}")
    st, d = rest(f"/wp-json/wp/v2/posts/{x['id']}", "POST", {"slug": baru})
    if not isinstance(d, dict) or d.get("id") != x["id"]:
        print(f"    ❌ gagal HTTP {st} {str(d)[:120]}")
        continue
    time.sleep(2)
    st_baru, tujuan_baru = cek(d["link"])
    st_lama, tujuan_lama = cek(x["link"])
    print(f"    URL baru: HTTP {st_baru} {tujuan_baru[:70]}")
    print(f"    URL lama: HTTP {st_lama} → {tujuan_lama[:70]}")
    if st_lama in (301, 302, 308):
        print("    ✅ WordPress mengalihkan URL lama otomatis")
    else:
        print(f"    ⚠ URL lama TIDAK dialihkan (HTTP {st_lama}) — butuh pengalihan manual")
