#!/usr/bin/env python3
"""Cache SEMUA jadwal (semua akun) ke file JSON — dipakai untuk cek slot + anti-redundant."""
import json, sys, time
sys.path.insert(0, "/home/mantapman/.hermes/profiles/atun/workspace")
from repliz_client import get_client

OUT = sys.argv[1] if len(sys.argv) > 1 else "/home/mantapman/.hermes/profiles/atun/workspace/_cache_sched_threads_17okt.json"
client = get_client()
docs = []
for p in range(1, 80):
    got = None
    for i in range(15):
        try:
            got = client.get_schedules(page=p, limit=100)
            break
        except Exception as e:
            print(f"retry p{p}/{i}: {str(e)[:60]}", flush=True)
            time.sleep(min(30, 3 + 3 * i))
    if got is None:
        raise SystemExit(f"gagal halaman {p}")
    b = got.get("docs", [])
    if not b:
        break
    docs.extend(b)
    print(f"page {p}: +{len(b)} (total {len(docs)})", flush=True)
    if len(b) < 100:
        break

slim = [{"accountId": d.get("accountId"), "_id": d.get("_id"), "scheduleAt": d.get("scheduleAt"),
         "status": d.get("status"), "description": d.get("description"),
         "title": d.get("title"), "topic": d.get("topic"), "type": d.get("type")} for d in docs]
json.dump(slim, open(OUT, "w"), ensure_ascii=False)
print("saved", len(slim), "->", OUT)
