#!/usr/bin/env python3
"""Riwayat jadwal Threads tslaw/tsc/das 18-23 Sep (WIB) — siapa yang bikin apa."""
import sys, time
from datetime import datetime, timedelta, timezone

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

WIB = timezone(timedelta(hours=7))
client = get_client()
ACC_MAP = {
    "studiosoft": ACC.STUDIOSOFT_THREADS,
    "uky": ACC.UKY_THREADS,
    "tslaw": ACC.TSLAW_THREADS,
    "tsc": ACC.TSC_THREADS,
    "das": ACC.DAS_THREADS,
}
IDS = {v: k for k, v in ACC_MAP.items()}

all_docs = []
for p in range(1, 200):
    got = None
    for i in range(15):
        try:
            got = client.get_schedules(page=p, limit=100)
            break
        except Exception as e:
            print(f"  retry page {p}: {str(e)[:60]}", file=sys.stderr)
            time.sleep(min(40, 3 + 4 * i))
    if got is None:
        raise RuntimeError(f"page {p} gagal")
    b = got.get("docs", [])
    if not b:
        break
    all_docs.extend(b)
    if len(b) < 100:
        break

def wib(sa):
    if not sa:
        return None
    try:
        return datetime.fromisoformat(str(sa).replace("Z", "+00:00")).astimezone(WIB)
    except Exception:
        return None

rows = []
for d in all_docs:
    aid = d.get("accountId")
    if aid not in IDS:
        continue
    t = wib(d.get("scheduleAt"))
    if not t or not ("2026-09-18" <= t.strftime("%Y-%m-%d") <= "2026-09-23"):
        continue
    rows.append((t, IDS[aid], d))
rows.sort(key=lambda x: (x[0], x[1]))
cur = None
for t, acc, d in rows:
    day = t.strftime("%Y-%m-%d")
    if day != cur:
        cur = day
        print(f"\n########## {day} ##########")
    c = wib(d.get("createdAt")) if d.get("createdAt") else None
    print(f"  {acc:11} {t.strftime('%H:%M')} {d.get('status'):9} type={str(d.get('type')):6} created={c.strftime('%d/%m %H:%M') if c else '?'} title={(d.get('title') or '')[:45]}")
