#!/usr/bin/env python3
"""Cek jadwal Threads @ukyhandoko: slot 08:00 WIB, riwayat uky_thread images, duplikat 05_white_brand."""
import json, sys, time, urllib.request
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 v is None: return None, None
    if isinstance(v, (int, float)):
        return datetime.fromtimestamp(v/1000, tz=timezone.utc), v
    try:
        dt = datetime.fromisoformat(str(v).replace("Z", "+00:00"))
        return dt, v
    except Exception:
        return None, v

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):
        rr = c.get_schedules(page=p, limit=100)
        docs.extend(rr["docs"])
    print(f"fetched {len(docs)} jadwal total")

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

    # ── 1) duplikat 05_white_brand / image pipeline (semua status) ──
    print("\n── item image pipeline uky_thread (semua status) ──")
    for d in sorted(mine, key=lambda x: (parse_at(x.get("scheduleAt"))[0] or datetime.min)):
        meds = d.get("medias") or []
        url = (meds[0].get("url") if meds else "") or ""
        hay = url + " " + (d.get("title") or "") + " " + (d.get("description") or "")
        if "white_brand" in hay or "white_leadership" in hay or "uky_thread" in hay:
            dt, raw = parse_at(d.get("scheduleAt"))
            ts = dt.strftime("%Y-%m-%d %H:%M WIB") if dt else f"raw={raw}"
            print(f"  id={d.get('id')} status={d.get('status')} at={ts}")
            print(f"    type={d.get('type')} media={url[:110]}")
            print(f"    title={ (d.get('title') or '')[:80]!r}")
            print(f"    desc={ (d.get('description') or '')[:150]!r}")

    # ── 2) jadwal pending masa depan (Sep 5-8) ──
    print("\n── pending/future Sep 5-9 2026 ──")
    now = datetime.now(timezone.utc)
    for d in sorted(mine, key=lambda x: (parse_at(x.get("scheduleAt"))[0] or datetime.min)):
        dt, _ = parse_at(d.get("scheduleAt"))
        if not dt: continue
        st = (d.get("status") or "").lower()
        if dt >= now and dt <= datetime(2026, 9, 10, tzinfo=timezone.utc):
            meds = d.get("medias") or []
            url = (meds[0].get("url") if meds else "") or ""
            print(f"  id={d.get('id')} status={st} at={dt.strftime('%Y-%m-%d %H:%M')} UTC ({ (dt+WIB).strftime('%Y-%m-%d %H:%M') } WIB) type={d.get('type')}")
            print(f"    media={url[:110]}")
            print(f"    title={ (d.get('title') or '')[:70]!r} replies={len(d.get('replies') or [])}")

if __name__ == "__main__":
    main()
