#!/usr/bin/env python3
"""Tag TSC bernama lama: dikumpulkan lewat daftar tag pada tiap artikel (endpoint /tags polos diblokir).

--go : ganti nama tag lama, hapus tag rusak (nama berisi koma / sangat panjang).
"""
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"}


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()[:160]
        except Exception:
            time.sleep(3)
    return 0, "gagal"


ids = set()
for jenis in ("posts", "pages"):
    page = 1
    while True:
        st, d = rest(f"/wp-json/wp/v2/{jenis}?per_page=100&page={page}&status=publish&_fields=id,tags")
        if not isinstance(d, list) or not d:
            break
        for x in d:
            for t in (x.get("tags") or []):
                ids.add(t)
        if len(d) < 100:
            break
        page += 1
print(f"tag unik dari artikel: {len(ids)}")

tags = []
for i, tid in enumerate(sorted(ids), 1):
    st, t = rest(f"/wp-json/wp/v2/tags/{tid}?_fields=id,name,slug,count")
    if isinstance(t, dict) and "id" in t:
        tags.append(t)
    if i % 100 == 0:
        print(f"   ...{i}/{len(ids)}")

kena = [t for t in tags if re.search(r"dni", t["slug"], re.I) or re.search(r"\bdni\b|klinik dni", t["name"], re.I)]
print(f"\ntag bernama lama: {len(kena)}")


def usul(nama):
    n = nama
    n = re.sub(r"klinik\s*dni\s*krian\s*sidoarjo", "The Skin Code Clinic Krian Sidoarjo", n, flags=re.I)
    n = re.sub(r"klinik\s*dni\s*krian", "The Skin Code Clinic Krian", n, flags=re.I)
    n = re.sub(r"klinik\s*dni\s*sidoarjo", "The Skin Code Clinic Sidoarjo", n, flags=re.I)
    n = re.sub(r"klinik\s*dni", "The Skin Code Clinic", n, flags=re.I)
    n = re.sub(r"\bDNI\s+Krian\b", "The Skin Code Clinic", n, flags=re.I)
    n = re.sub(r"\bDNI\b", "The Skin Code Clinic", n, flags=re.I)
    return re.sub(r"\s{2,}", " ", n).strip()


rencana = []
for t in sorted(kena, key=lambda y: -y["count"]):
    rusak = t["name"].count(",") > 0 or len(t["name"]) > 60
    baru = None if rusak else usul(t["name"])
    aksi = "hapus" if rusak else ("ganti" if baru != t["name"] else "biarkan")
    rencana.append({"id": t["id"], "name": t["name"], "slug": t["slug"], "count": t["count"],
                    "aksi": aksi, "baru": baru})
    print(f"  #{t['id']:<5} {t['count']:>4} artikel | {t['name'][:66]}")
    print(f"        → {aksi.upper()}: {baru or '(dihapus)'}")

json.dump(rencana, open(f"{WS}/drafts/tsc_tag_rencana.json", "w"), ensure_ascii=False, indent=1)
if "--go" not in sys.argv:
    print("\n(dry run — pakai --go)")
    sys.exit(0)

for r in rencana:
    if r["aksi"] == "hapus":
        st, _ = rest(f"/wp-json/wp/v2/tags/{r['id']}?force=true", "DELETE")
        print(f"  hapus #{r['id']} «{r['name'][:44]}» → HTTP {st}")
    elif r["aksi"] == "ganti":
        st, d = rest(f"/wp-json/wp/v2/tags/{r['id']}", "POST", {"name": r["baru"]})
        slug_baru = d.get("slug") if isinstance(d, dict) else "?"
        print(f"  ganti #{r['id']} → «{r['baru']}» (slug {slug_baru}) HTTP {st}")
    time.sleep(0.3)
