#!/usr/bin/env python3
"""Cek state LEIT Surabaya di Repliz: akun + jadwal pending/upcoming."""
import sys, os, json
from datetime import datetime, timezone
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from repliz_client import get_client, ACC

c = get_client()
acc_map = {
    ACC.LEIT_FB: "LEIT_FB", ACC.LEIT_IG: "LEIT_IG",
    ACC.LEIT_LINKEDIN: "LEIT_LINKEDIN", ACC.LEIT_THREADS: "LEIT_THREADS",
    ACC.LEIT_TIKTOK: "LEIT_TIKTOK",
}
now = datetime.now(timezone.utc)
out = {name: {"pending_future": [], "error": 0, "success": 0} for name in acc_map.values()}
page = 1
total = 0
while True:
    r = c.get_schedules(page=page, limit=100)
    docs = r.get("docs", [])
    total += len(docs)
    for d in docs:
        acc = d.get("accountId")
        if acc not in acc_map:
            continue
        name = acc_map[acc]
        st = d.get("status")
        if st == "error":
            out[name]["error"] += 1
        elif st == "success":
            out[name]["success"] += 1
        else:
            sa = d.get("scheduleAt", "")
            try:
                dt = datetime.fromisoformat(sa.replace("Z", "+00:00"))
            except Exception:
                continue
            if dt >= now:
                out[name]["pending_future"].append((sa, d.get("_id"), d.get("type"), (d.get("description") or "")[:60]))
    if len(docs) < 100:
        break
    page += 1

print(f"total schedules: {total}  (now UTC {now.isoformat()})")
for name, v in out.items():
    pf = sorted(v["pending_future"])
    print(f"\n== {name}: pending_future={len(pf)} success={v['success']} error={v['error']}")
    for row in pf[:6]:
        print("   ", row[0], row[2], row[1], row[3].replace("\n", " "))
    if pf:
        print("    LAST:", pf[-1][0])
json.dump({k: {"pending_future": sorted(v["pending_future"]), "success": v["success"], "error": v["error"]} for k, v in out.items()},
          open("leit_state_20260917.json", "w"), indent=1)
