#!/usr/bin/env python3
"""Cek status semua jadwal Repliz untuk 1 akun (default: TSC IG).
Usage: python3 cek_status_akun.py [account_key]
"""
import sys, json
from datetime import datetime, timedelta, timezone

sys.path.insert(0, "/home/mantapman/.hermes/profiles/atun/workspace")
from repliz_client import get_client, ACCOUNTS

key = sys.argv[1] if len(sys.argv) > 1 else "tsc_ig"
acc_id = ACCOUNTS[key]
print(f"akun: {key} -> {acc_id}")

c = get_client()
first = c.get_schedules(page=1, limit=100)
total = first.get("totalDocs", 0)
pages = (total + 99) // 100
docs = list(first.get("docs", []))
for p in range(2, pages + 1):
    docs.extend(c.get_schedules(page=p, limit=100).get("docs", []))
print(f"total jadwal semua akun: {total} (fetched {len(docs)})")

mine = [d for d in docs if (d.get("account") or {}).get("id") == acc_id
        or (d.get("accountId") == acc_id) or (d.get("account") or {}).get("_id") == acc_id]

def wib(s):
    if not s:
        return "-"
    try:
        dt = datetime.fromisoformat(s.replace("Z", "+00:00")) + timedelta(hours=7)
        return dt.strftime("%Y-%m-%d %H:%M")
    except Exception:
        return s

from collections import Counter
cnt = Counter((d.get("status") or "?").lower() for d in mine)
print(f"\njadwal akun ini: {len(mine)}")
for k, v in cnt.most_common():
    print(f"  {k}: {v}")

mine.sort(key=lambda d: d.get("scheduleAt") or "")
print("\n--- detail ---")
for d in mine:
    med = d.get("medias") or []
    txt = (d.get("title") or d.get("description") or "").replace("\n", " ")[:70]
    print(f"{wib(d.get('scheduleAt'))} | {d.get('status')} | {d.get('type')} | media={len(med)} | {d.get('id')} | {txt}")

with open("/home/mantapman/.hermes/profiles/atun/workspace/cek_status_%s.json" % key, "w") as f:
    json.dump(mine, f, indent=1, ensure_ascii=False)
