#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""audit_story_9x16.py — audit SEMUA jadwal `story` yang masih pending: medianya bukan 9:16?

Story IG/FB memaksa media memenuhi kanvas 9:16 → gambar 4:5/1:1/16:9 akan terpotong.
Read-only. Untuk tiap jadwal story pending ke depan: cetak akun, jam WIB, jenis media,
nama file, ukuran (kalau file ada lokal di openclaw-img/), dan status temuan.
"""
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

WIB = datetime.timezone(datetime.timedelta(hours=7))
IMG_DIR = os.path.join(WS, "openclaw-img")
AKUN = {}


def semua(c):
    docs, page = [], 1
    while page <= 80:
        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


c = get_client()
try:
    r = c.get("/public/account?page=1&limit=100")
    for acc in (r.get("docs") or []):
        AKUN[acc.get("_id") or acc.get("id")] = acc.get("name") or acc.get("username") or "?"
except Exception as e:
    print("(gagal ambil daftar akun:", e, ")")

docs = semua(c)
now = datetime.datetime.now(datetime.timezone.utc)
temuan = 0
for d in docs:
    if str(d.get("type")).lower() != "story":
        continue
    if str(d.get("status") or "").lower() not in ("pending", "draft"):
        continue
    sa = str(d.get("scheduleAt") or "").replace("Z", "+00:00")
    try:
        dt = datetime.datetime.fromisoformat(sa)
    except Exception:
        continue
    if dt <= now:
        continue
    meds = d.get("medias") or []
    if not meds:
        continue
    nama = (meds[0].get("url") or "").split("/")[-1]
    if nama.lower().endswith((".mp4", ".mov", ".m4v")):
        continue
    p = os.path.join(IMG_DIR, nama)
    uk = "-"
    if os.path.exists(p):
        try:
            from PIL import Image
            with Image.open(p) as im:
                uk = f"{im.size[0]}x{im.size[1]}"
        except Exception as e:
            uk = f"ERR {e}"
    akun = AKUN.get(d.get("accountId"), d.get("accountId"))
    flag = ""
    if uk not in ("-", "1080x1920", "720x1280", "1080x1080", "1170x2532", "1440x2560"):
        flag = "  <<< BUKAN 9:16"
        temuan += 1
    print(f"{dt.astimezone(WIB):%d %b %H:%M} WIB | {str(akun)[:22]:22s} | {uk:10s} | {nama[:48]:48s}{flag}")

print(f"\ntotal temuan media story bukan 9:16: {temuan}")
