#!/usr/bin/env python3
"""Kumpulkan tag TSC lewat endpoint tag per-artikel (lebih cepat), lalu ganti nama yang masih lama.

--go : jalankan perubahan.
"""
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"


posts, page = [], 1
while True:
    st, d = rest(f"/wp-json/wp/v2/posts?per_page=100&page={page}&status=publish&_fields=id")
    if not isinstance(d, list) or not d:
        break
    posts += [x["id"] for x in d]
    if len(d) < 100:
        break
    page += 1
print(f"artikel: {len(posts)}", flush=True)

tags = {}
for i, pid in enumerate(posts, 1):
    st, d = rest(f"/wp-json/wp/v2/tags?post={pid}&per_page=100&_fields=id,name,slug,count")
    if isinstance(d, list):
        for t in d:
            tags[t["id"]] = t
    if i % 40 == 0:
        print(f"   ...{i}/{len(posts)} (tag terkumpul {len(tags)})", flush=True)

print(f"tag unik: {len(tags)}", flush=True)
kena = [t for t in tags.values() if re.search(r"dni", t["slug"], re.I) or re.search(r"dni", t["name"], re.I)]
print(f"tag 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.get("count", 0)):
    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.get("count"),
                    "aksi": aksi, "baru": baru})
    print(f"  #{t['id']:<5} {t.get('count'):>4} | {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}", flush=True)
    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}", flush=True)
    time.sleep(0.3)
