#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Ganti LABEL/topic jadwal Threads @ukyhandoko yang bertanda 'growth'.

Perintah Bos 4 Okt 2026: "Itu threads jangan kategori growth uky".

topic 'Growth uky' / 'uky Growth2' -> label sesuai isi:
  Q (pertanyaan)  -> Diskusi & Tanya
  O (opini)       -> Opini Bisnis
  T (tips/cerita) -> Tips & Pengalaman
title juga dibersihkan dari kata 'growth' ("Growth uky Q 2026-10-05" -> "uky Q 2026-10-05").

Pakai: python3 ganti_label_growth_uky.py          # dry run
       python3 ganti_label_growth_uky.py --run    # eksekusi (PUT)
"""
import re
import sys
import time
from repliz_client import get_client

UKY = "6a334e89c5ff4ce3a3225a48"
PETA = {"Q": "Diskusi & Tanya", "O": "Opini Bisnis", "T": "Tips & Pengalaman"}


def semua_jadwal(c):
    docs, page = [], 1
    while True:
        r = c.get_schedules(page=page, limit=100)
        d = r.get("docs") or []
        docs.extend(d)
        if not d or len(docs) >= (r.get("totalDocs") or 0) or page > 60:
            break
        page += 1
    return docs


def tipe_dari(judul):
    m = re.search(r"\b([QOT])\b", judul or "")
    return m.group(1) if m else None


def main():
    run = "--run" in sys.argv
    c = get_client()
    rows = semua_jadwal(c)
    sasaran = []
    for x in rows:
        if (x.get("accountId") or (x.get("account") or {}).get("_id")) != UKY:
            continue
        top = (x.get("topic") or "").lower()
        if "growth" not in top or x.get("type") != "text":
            continue
        tipe = tipe_dari(x.get("title"))
        if not tipe:
            print("⚠️ tipe tak dikenali:", x.get("_id"), repr(x.get("title")))
            continue
        tgl = ((x.get("scheduleAt") or "")[:10])
        sasaran.append({"id": x.get("_id"), "tipe": tipe, "tgl": tgl,
                        "topic_lama": x.get("topic"), "title_lama": x.get("title"),
                        "topic_baru": PETA[tipe], "title_baru": f"uky {tipe} {tgl}",
                        "status": x.get("status")})

    print(f"jadwal uky bertopic 'growth': {len(sasaran)}")
    for s in sorted(sasaran, key=lambda z: z["tgl"]):
        print(f"  {s['tgl']} [{s['tipe']}] {s['topic_lama']!r} -> {s['topic_baru']!r} | "
              f"title {s['title_lama']!r} -> {s['title_baru']!r} | {s['status']} {s['id']}")
    if not run:
        print("\n(dry run — tambahkan --run untuk eksekusi)")
        return

    ok = gagal = 0
    for s in sasaran:
        try:
            r = c.update_schedule(s["id"], {"topic": s["topic_baru"], "title": s["title_baru"]})
            ok += 1
        except Exception as e:  # noqa: BLE001
            gagal += 1
            print("❌", s["id"], type(e).__name__, str(e)[:160])
        time.sleep(0.3)
    print(f"\nselesai: ok {ok} | gagal {gagal}")

    # verifikasi baca balik
    rows2 = semua_jadwal(c)
    sisa = [x for x in rows2
            if (x.get("accountId") or (x.get("account") or {}).get("_id")) == UKY
            and x.get("type") == "text" and "growth" in (x.get("topic") or "").lower()]
    print("sisa jadwal uky bertopic 'growth':", len(sisa))
    for s in sasaran[:5]:
        cur = c.get_schedule(s["id"]) or {}
        print(f"  cek {s['id']}: topic={cur.get('topic')!r} title={cur.get('title')!r} "
              f"status={cur.get('status')} jadwal={cur.get('scheduleAt')}")


if __name__ == "__main__":
    main()
