#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Cek jadwal Threads 5 akun untuk tanggal tertentu (default hari ini WIB)."""
import sys, json
from datetime import datetime, timedelta, timezone

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

WIB = timezone(timedelta(hours=7))
TARGET = sys.argv[1] if len(sys.argv) > 1 else datetime.now(WIB).strftime("%Y-%m-%d")

ACC_MAP = {
    "studiosoft": ACC.STUDIOSOFT_THREADS,
    "uky": ACC.UKY_THREADS,
    "tslaw": ACC.TSLAW_THREADS,
    "tsc": ACC.TSC_THREADS,
    "das": ACC.DAS_THREADS,
}

c = get_client()
docs = []
for p in range(1, 150):
    r = c.get_schedules(page=p, limit=100)
    b = r.get("docs", [])
    if not b:
        break
    docs += b
    if len(b) < 100:
        break
print("total schedules:", len(docs), "| target:", TARGET)

name_by_id = {v: k for k, v in ACC_MAP.items()}
rows = []
for d in docs:
    aid = d.get("accountId")
    if aid not in name_by_id:
        continue
    sa = d.get("scheduleAt")
    if not sa:
        continue
    try:
        dt = datetime.fromisoformat(str(sa).replace("Z", "+00:00")).astimezone(WIB)
    except Exception:
        continue
    if dt.strftime("%Y-%m-%d") != TARGET:
        continue
    desc = d.get("description") or ""
    rows.append((dt.hour, name_by_id[aid], d.get("status"), d.get("type"),
                 d.get("_id"), (d.get("title") or "")[:40], desc[:90].replace("\n", " ")))
rows.sort()
for h, name, st, ty, sid, title, desc in rows:
    print(f"  {h:02d}:00 WIB | {name:11} | {st:8} | {ty} | {sid} | {title} | {desc}")
print("total untuk", TARGET, ":", len(rows))
