#!/usr/bin/env python3
"""Cek slot 08:00 WIB Threads @ukyhandoko + bentrok media 13_orange_website (read-only).
Dipakai cron 13 Sep 2026 18:00Z untuk item index 43.
"""
import 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)
TARGET_BASE = "13_orange_website"


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)
    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)

    print("\n── 08:00 WIB terisi (>= hari ini) ──")
    for k in sorted(bydate):
        if k < (now + WIB).strftime("%Y-%m-%d"):
            continue
        for d in bydate[k]:
            meds = d.get("medias") or []
            url = (meds[0].get("url") if meds else "") or ""
            print(f"  {k} | {d.get('status'):8s} type={str(d.get('type')):6s} media={url.split('/')[-1][:60]}")

    print("\n── bentrok media 13_orange_website (semua status, akun uky) ──")
    for d in mine:
        meds = d.get("medias") or []
        url = (meds[0].get("url") if meds else "") or ""
        import os
        base = os.path.basename(url.split("?")[0]).lower()
        if base == TARGET_BASE + ".jpg" or base == TARGET_BASE + ".png":
            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={base}")

    print("\n── kandidat slot 08:00 WIB bebas (3 Sep-31 Okt) ──")
    for day in range(0, 60):
        d0 = datetime(2026, 9, 1, 1, 0, tzinfo=timezone.utc) + timedelta(days=day - 1)
        key = (d0 + WIB).strftime("%Y-%m-%d")
        if key < (now + WIB).strftime("%Y-%m-%d"):
            continue
        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()
