#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Probe jadwal IG StudioSoft: cari jadwal type=story yang medianya BUKAN 9:16 (akan kepotong).

Read-only. Cetak per jadwal: id, status, jam WIB, type, nama media, ukuran file lokal (kalau ada),
URL media.
"""
import datetime
import os
import sys
import time

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

IG_SS = "6a38ac33c5ff4ce3a3231232"
WIB = datetime.timezone(datetime.timedelta(hours=7))
IMG_DIR = os.path.join(WS, "openclaw-img")
HANYA_STORY = "--semua" not in sys.argv


def semua(c):
    docs, page = [], 1
    while page <= 60:
        r = None
        for a in range(5):
            try:
                r = c.get_schedules(page=page, limit=100)
                break
            except Exception:
                time.sleep(4 + 2 * a)
        if r is None:
            raise SystemExit("gagal baca jadwal")
        b = r.get("docs") or []
        docs += b
        if len(b) < 100:
            break
        page += 1
    return docs


def ukuran(nama):
    p = os.path.join(IMG_DIR, nama)
    if not os.path.exists(p):
        return "-"
    try:
        from PIL import Image
        with Image.open(p) as im:
            return f"{im.size[0]}x{im.size[1]}"
    except Exception as e:
        return f"ERR {e}"


c = get_client()
docs = [d for d in semua(c) if d.get("accountId") == IG_SS]
sekarang = datetime.datetime.now(datetime.timezone.utc)
rows = []
for d in docs:
    t = str(d.get("scheduleAt") or "").replace("Z", "+00:00")
    try:
        dt = datetime.datetime.fromisoformat(t)
    except Exception:
        dt = None
    tipe = str(d.get("type") or "").lower()
    if HANYA_STORY and tipe != "story":
        continue
    meds = d.get("medias") or []
    nama = (meds[0].get("url") or "").split("/")[-1] if meds else ""
    rows.append((dt, tipe, d.get("status"), d.get("_id"), nama, ukuran(nama), d.get("title")))

rows.sort(key=lambda r: (r[0] is None, r[0]))
print(f"total jadwal akun IG SS: {len(docs)} | baris ditampilkan: {len(rows)} | sekarang {sekarang.astimezone(WIB):%d %b %H:%M} WIB\n")
for dt, tipe, status, sid, nama, uk, judul in rows:
    jam = dt.astimezone(WIB).strftime("%d %b %H:%M") if dt else "?"
    tanda = ""
    if dt and dt > sekarang and status in ("pending", "draft") and uk not in ("-", "1080x1920", "720x1280", "1080x1080"):
        tanda = "  <<< BUKAN 9:16"
    print(f"{jam} | {status:9s} | {tipe:6s} | {uk:10s} | {nama[:52]:52s} | {judul or ''}{tanda}")
