#!/usr/bin/env python3
"""Offboarding: hapus SELURUH jadwal Repliz milik LEIT dan Warung Pak Otto (Soto).
Pakai --apply untuk benar-benar menghapus."""
import json, sys, time
from collections import Counter

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
sys.path.insert(0, WS)
from repliz_client import get_client, ACC          # noqa: E402

NAMA = {getattr(ACC, n): n for n in dir(ACC) if not n.startswith("_")}
client = get_client()

# akun milik klien yang diputus kontraknya
TARGET = {
    "6a8f9df162caae1e040754d8": "SOTO_FB",
    "6a86d84b62caae1e04fff12c": "SOTO_THREADS",
    "6a86d70362caae1e04ffedef": "SOTO_TIKTOK",
    "6a86d6e962caae1e04ffedaa": "SOTO_IG",
    "6a82c69a62caae1e04fbde9c": "LEIT_TIKTOK",
    "6a618e9262caae1e04e99518": "LEIT_FB",
    "6a60451662caae1e04e91040": "LEIT_LINKEDIN",
    "6a5f4af462caae1e04e8b9a6": "LEIT_THREADS",
    "6a7d765862caae1e04f7ded3": "LEIT_IG",
}

print("=== mengumpulkan jadwal ===")
sasaran = []
page = 1
while True:
    d = client.get_schedules(page=page, limit=100)
    docs = d.get("docs", []) if isinstance(d, dict) else []
    for s in docs:
        if s.get("accountId") in TARGET:
            sasaran.append(s)
    if len(docs) < 100:
        break
    page += 1

per_akun = Counter(TARGET[s["accountId"]] for s in sasaran)
per_status = Counter(s.get("status") for s in sasaran)
print(f"jadwal sasaran: {len(sasaran)}")
for a, n in per_akun.most_common():
    print(f"   {a:<18} {n}")
print(f"per status: {dict(per_status)}")

if "--apply" not in sys.argv:
    print("\n(dry run — pakai --apply untuk menghapus)")
    sys.exit(0)

print(f"\n=== menghapus {len(sasaran)} jadwal ===")
ok = gagal = 0
for i, s in enumerate(sasaran, 1):
    sid = s.get("_id")
    try:
        client.delete_schedule(sid)
        ok += 1
    except Exception as e:
        gagal += 1
        print(f"   ❌ {sid} ({TARGET.get(s.get('accountId'))}): {str(e)[:70]}")
    if i % 25 == 0 or i == len(sasaran):
        print(f"   {i}/{len(sasaran)} | terhapus {ok} | gagal {gagal}")
    time.sleep(0.25)

print("\n=== verifikasi: baca ulang seluruh jadwal ===")
sisa = []
page = 1
while True:
    d = client.get_schedules(page=page, limit=100)
    docs = d.get("docs", []) if isinstance(d, dict) else []
    for s in docs:
        if s.get("accountId") in TARGET:
            sisa.append(s)
    if len(docs) < 100:
        break
    page += 1
print(f"   jadwal tersisa milik klien yang diputus: {len(sisa)}")
if sisa:
    print(f"   rincian: {dict(Counter(TARGET.get(s.get('accountId'), s.get('accountId')) for s in sisa))}")
else:
    print("   ✅ bersih — tidak ada jadwal tersisa")
