#!/usr/bin/env python3
"""Posting info menu Pak Otto: Tempe Mendoan 2rb + Lumpia Semarang 7rb + tagline Pagerwojo."""
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]
OTTO = {
    "6a86d6e962caae1e04ffedaa": "IG",
    "6a86d70362caae1e04ffedef": "TikTok",
    "6a8f9df162caae1e040754d8": "FB",
    "6a86d84b62caae1e04fff12c": "Threads",
}

CAP = (
    "Siapa bilang nikmatnya Semarang harus ke Semarang? 😏\n\n"
    "Di Warung Pak Otto Pagerwojo Sidoarjo ada:\n"
    "🍜 Soto Ayam Kampung — Rp10 ribu PAS\n"
    "🥟 Lumpia Semarang — Rp7 ribu an\n"
    "🍢 Tempe Mendoan — cuma Rp2 ribuan!\n\n"
    "Ga perlu ke Semarang, cukup ke Pagerwojo Sidoarjo! 😋\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"
    "Paling suka nyamil yang mana: lumpia apa mendoan? Yuk jawab di komentar! 👇\n\n"
    "#SotoSemarangPakOtto #LumpiaSemarang #TempeMendoan #KulinerSidoarjo #KulinerMurah #PagerwojoSidoarjo"
)

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(14):
        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, nm, at, image=None):
    payload = {
        "accountId": accid,
        "title": f"Soto Pak Otto — Menu (Lumpia 7rb, Mendoan 2rb)",
        "description": CAP,
        "topic": "Menu",
        "type": "image" if image else "text",
        "medias": [{"url": image, "type": "image", "alt": "menu"} ] if image else [],
        "scheduleAt": at,
        "replies": [
            {"text": "Lumpia hangat + mendoan garing = nyamil paling pas sambil nunggu soto. 🥟🍢", "username": ""},
            {"text": "Tag teman yang hobi kulineran murah di Sidoarjo! 👇", "username": ""},
        ],
    }
    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 accid, nm in OTTO.items():
    pend = get_pending(accid)
    slot = next_free_slot(pend, now)
    if slot is None:
        print(f"  ❌ {nm}: tidak ada slot")
        fail += 1
        continue
    at = slot.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
    try:
        create(accid, nm, at)
        ok += 1
        print(f"  ✅ {nm:8s} | {slot.strftime('%d/%m %H:00')} WIB | menu lumpia 7rb + mendoan 2rb")
    except Exception as e:
        fail += 1
        print(f"  ❌ {nm}: {e}")
print(f"\n📊 Total: {ok} OK, {fail} gagal")
