#!/usr/bin/env python3
"""Daftar artikel TSC yang slug-nya masih memuat nama lama, untuk disusun rencana penggantiannya."""
import base64, importlib.util, json, re, 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"}


def rest(path):
    h = {"Authorization": f"Basic {AUTH}", **UA}
    r = urllib.request.Request(f"https://{DOM}{path}", headers=h)
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=120) as x:
                return json.loads(x.read())
        except urllib.error.HTTPError as e:
            return {"err": e.code}
        except Exception:
            time.sleep(4)
    return {}


baris = []
for jenis in ("posts", "pages"):
    page = 1
    while True:
        d = rest(f"/wp-json/wp/v2/{jenis}?per_page=100&page={page}&status=publish&_fields=id,slug,link,title,date")
        if not isinstance(d, list) or not d:
            break
        for x in d:
            if re.search(r"klinik[\s-]*dni", x["slug"], re.I):
                baris.append(x)
        if len(d) < 100:
            break
        page += 1

print(f"konten dengan slug nama lama: {len(baris)}\n")
for x in sorted(baris, key=lambda y: y["slug"]):
    print(f"  #{x['id']:<6} {x['slug']}")

json.dump(baris, open(f"{WS}/drafts/tsc_slug_lama.json", "w"), ensure_ascii=False, indent=1)

# usulan slug baru
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("-")

print("\n=== usulan slug baru ===")
for x in sorted(baris, key=lambda y: y["slug"])[:50]:
    b = usul(x["slug"])
    tanda = "" if b != x["slug"] else "  (tidak berubah)"
    print(f"  {x['slug'][:70]}")
    print(f"    → {b[:70]}{tanda}")
