#!/usr/bin/env python3
"""Scan SEMUA jadwal pending yang media-nya dari studiosoft.id → simpan daftar ke JSON."""
import json, time
from repliz_client import ReplizClient

c = ReplizClient()
hasil = []
page = 1
total = None
while True:
    r = c.get_schedules(page=page, limit=100)
    docs = r.get("docs") or []
    total = r.get("totalDocs", total)
    for s in docs:
        if s.get("status") != "pending":
            continue
        urls = [m.get("url", "") for m in (s.get("medias") or [])]
        kena = [u for u in urls if "studiosoft.id/wp-content" in u]
        if kena:
            hasil.append({
                "id": s.get("_id") or s.get("id"),
                "accountId": s.get("accountId"),
                "accountName": ((s.get("account") or {}).get("name") or "")[:30],
                "title": (s.get("title") or s.get("topic") or "")[:60],
                "type": s.get("type"),
                "scheduleAt": s.get("scheduleAt"),
                "urls": kena,
            })
    if page * 100 >= (total or 0):
        break
    page += 1
    time.sleep(0.15)

with open("pending_studiosoft_media.json", "w") as f:
    json.dump({"total_docs": total, "kena": hasil}, f, indent=1)

# Ringkasan per akun
from collections import Counter
cnt = Counter(h["accountName"] or h["accountId"] for h in hasil)
print(f"Total jadwal pending dgn media studiosoft.id: {len(hasil)}")
for name, n in cnt.most_common():
    print(f"  {name}: {n}")
print("\n=== 20 pertama ===")
for h in hasil[:20]:
    print(h["scheduleAt"], "|", h["accountName"], "|", h["title"], "|", h["type"], "|", h["id"])
