#!/usr/bin/env python3
"""Lengkapi jadwal video Pak Otto yang belum tayang di 3 platform (IG+TikTok+FB)."""
import sys, json, urllib.request
from datetime import datetime, timedelta, timezone

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

WIB = timezone(timedelta(hours=7))
SLOTS = [5, 8, 11, 14, 17, 20, 23]
IMG_BASE = "https://mantapserver.tail3947bb.ts.net/openclaw-img/"

OTTO = {
    "6a86d6e962caae1e04ffedaa": "IG",
    "6a86d70362caae1e04ffedef": "TikTok",
    "6a8f9df162caae1e040754d8": "FB",
}

# video yang perlu dilengkapi: (file, akun yang kurang)
NEED = [
    ("soto_pakotto_video5.mp4", ["6a8f9df162caae1e040754d8"]),          # FB
    ("soto_reel_bos.mp4", ["6a86d70362caae1e04ffedef", "6a8f9df162caae1e040754d8"]),  # TikTok + FB
    ("soto_video_1.mp4", ["6a8f9df162caae1e040754d8"]),                 # FB
    ("soto_video_2.mp4", ["6a8f9df162caae1e040754d8"]),                 # FB
    ("soto_video_4.mp4", ["6a8f9df162caae1e040754d8"]),                 # FB
]

CAP = (
    "Soto Semarang Ayam Kampung yang hangatnya nempel di hati — pas banget buat nemenin malam minggu. 🍜✨\n\n"
    "Kuah bening gurih, ayam kampung empuk, plus sambal yang bikin nagih. Dijamin makin enak dinikmati ramai-ramai.\n\n"
    "📍 Jl. Graha Anggrek Mas No. C-16, Ruko Pagerwojo, Buduran, Sidoarjo\n"
    "⏰ Selasa–Minggu 10.00–21.00 WIB\n"
    "📲 081230777713\n\n"
    "Pernah cobain soto Semarang di sini? Yuk cerita di komentar, menu favorit kalian apa! 👇\n\n"
    "#SotoSemarangPakOtto #SotoSemarang #KulinerSidoarjo #KulinerMalem #WarungSemarang #SotoAyamKampung"
)

def get_pending(accid):
    pend = []
    for p in range(1, 60):
        raw = urllib.request.Request(f"{BASE}/public/schedule?page={p}&limit=100", headers=HEADERS)
        with urllib.request.urlopen(raw, timeout=30) as r:
            docs = json.load(r)["docs"]
        for d in docs:
            if d.get("accountId") == accid and (d.get("status") or "").lower() == "pending":
                pend.append(d)
    return pend

def next_free_slot(pend_list, now):
    day = now.replace(minute=0, second=0, microsecond=0)
    for _ in range(21):
        taken = {(d.get("scheduleAt") or "")[:13] for d in pend_list}
        for h in SLOTS:
            cand = day.replace(hour=h)
            if cand <= now:
                continue
            utc_h = cand.astimezone(timezone.utc).strftime("%Y-%m-%dT%H")
            if utc_h not in taken:
                return cand
        day += timedelta(days=1)
    return None

def create(accid, acc_name, fn, at):
    payload = {
        "accountId": accid,
        "title": f"Soto Pak Otto — {fn} ({acc_name})",
        "description": CAP,
        "topic": "Video Soto",
        "type": "video",
        "medias": [{"url": IMG_BASE + fn, "type": "video", "alt": fn}],
        "scheduleAt": at,
        "replies": [],
    }
    req = urllib.request.Request(f"{BASE}/public/schedule",
                                 data=json.dumps(payload).encode(),
                                 headers={**HEADERS, "Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=30) as r:
        return json.load(r)

now = datetime.now(WIB)
print(f"🕒 sekarang: {now.strftime('%d/%m %H:%M WIB')}\n")
ok = fail = 0
for fn, accids in NEED:
    for accid in accids:
        acc_name = OTTO[accid]
        pend = get_pending(accid)
        slot = next_free_slot(pend, now)
        if slot is None:
            print(f"  ❌ {fn} → {acc_name}: tidak ada slot")
            fail += 1
            continue
        at = slot.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
        try:
            res = create(accid, acc_name, fn, at)
            ok += 1
            print(f"  ✅ {fn} → {acc_name:6s} | {slot.strftime('%d/%m %H:00')} WIB")
        except Exception as e:
            fail += 1
            print(f"  ❌ {fn} → {acc_name}: {e}")
print(f"\n📊 Total: {ok} OK, {fail} gagal")
