#!/usr/bin/env python3
"""Cek slot 08:00 WIB Threads @ukyhandoko (pending/lampau) utk item image berikutnya.
Juga cek apakah media 12_white_filosofi sudah pernah dijadwalkan (idempotensi).
Read-only.
"""
import json, sys
from datetime import datetime, timezone, timedelta

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

UKY_T = "6a334e89c5ff4ce3a3225a48"
WIB = timedelta(hours=7)


def parse_at(v):
    if not v:
        return None
    try:
        return datetime.fromisoformat(str(v).replace("Z", "+00:00"))
    except Exception:
        return None


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

    mine = []
    for d in docs:
        acc = d.get("account") or {}
        accid = d.get("accountId") or acc.get("id") or acc.get("_id") or ""
        if accid == UKY_T:
            mine.append(d)
    print(f"jadwal Threads uky: {len(mine)}")

    now = datetime.now(timezone.utc)

    print("\n── semua jadwal uky pada 01:00 UTC (08:00 WIB) ──")
    bydate = {}
    for d in mine:
        dt = parse_at(d.get("scheduleAt"))
        if not dt:
            continue
        if dt.hour == 1 and dt.minute == 0:
            key = (dt + WIB).strftime("%Y-%m-%d")
            bydate.setdefault(key, []).append(d)
    for k in sorted(bydate):
        for d in bydate[k]:
            meds = d.get("medias") or []
            url = (meds[0].get("url") if meds else "") or ""
            tag = "PENDING" if d.get("status") == "pending" and parse_at(d.get("scheduleAt")) >= now else d.get("status")
            print(f"  {k} 08:00 WIB | {tag:8s} type={d.get('type'):6s} media={url.split('/')[-1][:60]}")

    print("\n── media 12_white_filosofi / 11_white_meaning di akun uky (semua status) ──")
    for d in mine:
        meds = d.get("medias") or []
        url = (meds[0].get("url") if meds else "") or ""
        hay = url + " " + (d.get("title") or "")
        if "12_white_filosofi" in hay or "11_white_meaning" in hay:
            dt = parse_at(d.get("scheduleAt"))
            print(f"  id={d.get('id')} status={d.get('status')} at={(dt+WIB).strftime('%Y-%m-%d %H:%M') if dt else '?'} WIB media={url.split('/')[-1]}")

    # slot bebas 08:00 WIB berikutnya (cek bentrok di akun uky sendiri)
    print("\n── kandidat slot 08:00 WIB bebas (19 Sep - 20 Okt) ──")
    for day in range(19, 51):
        d0 = datetime(2026, 9, 1, 1, 0, tzinfo=timezone.utc) + timedelta(days=day - 1)
        key = (d0 + WIB).strftime("%Y-%m-%d")
        occupied = [x for x in bydate.get(key, []) if x.get("status") in ("pending", "success", "error")]
        status = "TERISI: " + ",".join(f"{x.get('status')}/{x.get('type')}" for x in occupied) if occupied else "KOSONG"
        print(f"  {key} 08:00 WIB → {status}")


if __name__ == "__main__":
    main()
