#!/usr/bin/env python3
"""
Threads Pak Otto — share video/foto/link TikTok dari server (FIXED 8 Sep 2026, Bos).
Caption: humanis + ajak diskusi + ajak datang ke lokasi. Slot kosong 05-23 WIB.
"""
import sys, json, os, 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))
SOTO_T = "6a86d84b62caae1e04fff12c"
SLOTS = [5, 8, 11, 14, 17, 20, 23]
IMG_BASE = "https://mantapserver.tail3947bb.ts.net/openclaw-img/"
STATE = "/home/mantapman/.hermes/profiles/atun/workspace/soto_threads_share_state.json"
LOKASI = "📍 Jl. Graha Anggrek Mas No. C-16, Ruko Pagerwojo, Buduran, Sidoarjo"
JAM = "⏰ Buka Setiap Hari: 10.00 - 21.00 WIB"
WA = "📲 081230777713"

# stok dari server
ROOT = "/home/mantapman/.hermes/profiles/atun/workspace/openclaw-img"
vids = sorted([f for f in os.listdir(ROOT) if (f.startswith('soto_') or f.startswith('pakotto')) and f.endswith('.mp4') and 'thumb' not in f])
fotos = sorted([f for f in os.listdir(ROOT) if f.startswith('soto_') and f.endswith(('.jpg', '.png')) and 'thumb' not in f and 'manual' not in f])

# link tiktok utk reshare (dari akun resmi)
TIKTOK_LINKS = [
    ("https://www.tiktok.com/@sotosemarang.pakotto", "profil resmi Warung Pak Otto di TikTok"),
]

CAPTION_FOTO = {
    "soto_menu.jpg": "Menu andalan kami hari ini — soto ayam kampung hangat, tempe mendoan 2 ribuan, dan lumpia Semarang 7 ribuan! 🍜✨",
    "soto_feed_": "Seruput hangatnya soto Semarang ayam kampung — kuah bening gurih yang bikin kangen. 🍜😋",
    "soto_story_": "Momen hangat di Warung Pak Otto — tempat di mana rasa Semarang ketemu Sidoarjo. 🍜💛",
    "soto_zip_": "Nikmatnya soto Semarang asli, sekarang gak perlu jauh-jauh ke Semarang! 🍜✨",
}
def caption_foto(fn):
    for key, cap in CAPTION_FOTO.items():
        if fn.startswith(key):
            return cap
    return "Sajian hangat dari dapur Warung Pak Otto — fresh, gurih, dan penuh rasa. 🍜✨"

def caption_video(fn):
    return "Dari dapur kami, dengan sepenuh hati — soto Semarang ayam kampung yang selalu fresh! 🍜✨"

def caption_tiktok(url, label):
    return f"Buat kamu yang penasaran dengan keseruan di Warung Pak Otto, cek juga TikTok resmi kami! 🎵 {url}"

def diskusi():
    return ("Pernah mampir ke sini? Menu favorit kamu apa — soto, nasgor babat, atau lumpia? "
            "Cerita di komentar, dan mampir langsung yuk — kami tunggu! 😊")

def footer():
    return f"{LOKASI}\n{JAM}\n{WA}"

def compose_media(fn):
    if fn.endswith('.mp4'):
        return caption_video(fn) + "\n\n" + diskusi() + "\n\n" + footer() + "\n\n" + "#sotosemarangpakotto #sotosemarang #kulinersidoarjo #sotoayamkampung #warungsemarang", "video", [{"url": IMG_BASE + fn, "type": "video", "alt": fn}]
    return caption_foto(fn) + "\n\n" + diskusi() + "\n\n" + footer() + "\n\n" + "#sotosemarangpakotto #sotosemarang #kulinersidoarjo #sotoayamkampung #warungsemarang", "image", [{"url": IMG_BASE + fn, "type": "image", "alt": fn}]

def get_pending():
    out = []
    for p in range(1, 90):
        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") == SOTO_T and (d.get("status") or "").lower() == "pending":
                out.append(d)
    return out

def load_state():
    try:
        with open(STATE) as f:
            return json.load(f)
    except Exception:
        return {"posted": []}

def main():
    n = int(sys.argv[1]) if len(sys.argv) > 1 else 10
    st = load_state()
    used = set(st.get("posted", []))
    pend = get_pending()
    # file yg sudah dipakai di Threads (dari media jadwal)
    used_media = set()
    for d in pend:
        for m in (d.get("medias") or []):
            used_media.add(m.get("url", "").split("/")[-1])

    # bangun antrian: video belum → foto belum → tiktok (kalau masih kurang)
    queue = []
    for f in vids:
        if f not in used_media and f not in used:
            queue.append(("video", f))
    for f in fotos:
        if f not in used_media and f not in used:
            queue.append(("foto", f))
    print(f"📦 antrian: {len(queue)} (video+foto belum pernah di Threads)")

    taken = {(d.get("scheduleAt") or "")[:13] for d in pend}
    now = datetime.now(WIB)
    day = now.replace(minute=0, second=0, microsecond=0)

    ok = fail = 0
    idx = 0
    # sisipkan 1 link tiktok tiap ~5 konten media
    tiktok_used = set(st.get("posted_tiktok", []))
    for i in range(min(n, len(queue))):
        # tiap 5 konten, selipkan 1 link tiktok
        if i > 0 and i % 5 == 0:
            for url, label in TIKTOK_LINKS:
                if url not in tiktok_used:
                    slot = None
                    for _ in range(30):
                        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:
                                slot = cand
                                break
                        if slot:
                            break
                        day += timedelta(days=1)
                    if slot is None:
                        break
                    taken.add(slot.astimezone(timezone.utc).strftime("%Y-%m-%dT%H"))
                    at = slot.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
                    cap = caption_tiktok(url, label) + "\n\n" + diskusi() + "\n\n" + footer() + "\n\n#sotosemarangpakotto #sotosemarang #kulinersidoarjo"
                    payload = {
                        "accountId": SOTO_T, "title": "Pak Otto — TikTok", "description": cap,
                        "topic": "Reshare TikTok", "type": "text", "medias": [], "scheduleAt": at,
                        "replies": [{"text": "Follow TikTok kami ya — banyak konten seru dari dapur! 🎵", "username": ""}],
                    }
                    req = urllib.request.Request(f"{BASE}/public/schedule", data=json.dumps(payload).encode(), headers={**HEADERS, "Content-Type": "application/json"})
                    try:
                        with urllib.request.urlopen(req, timeout=30) as r:
                            res = json.load(r)
                        ok += 1
                        print(f"  ✅ {slot.strftime('%d/%m %H:00')} WIB | TikTok link")
                        st.setdefault("posted_tiktok", []).append(url)
                        with open(STATE, "w") as f:
                            json.dump(st, f, indent=1, ensure_ascii=False)
                    except Exception as e:
                        fail += 1
                        print(f"  ❌ tiktok: {e}")
                    break
        if idx >= len(queue):
            break
        kind, fn = queue[idx]
        idx += 1
        if fn in used_media or fn in used:
            continue
        slot = None
        for _ in range(30):
            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:
                    slot = cand
                    break
            if slot:
                break
            day += timedelta(days=1)
        if slot is None:
            break
        taken.add(slot.astimezone(timezone.utc).strftime("%Y-%m-%dT%H"))
        at = slot.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
        cap, mtype, medias = compose_media(fn)
        payload = {
            "accountId": SOTO_T, "title": f"Pak Otto — {fn}", "description": cap,
            "topic": "Konten Soto", "type": mtype, "medias": medias, "scheduleAt": at,
            "replies": [{"text": "Sampai jumpa di Pagerwojo ya! Kami buka setiap hari 10.00-21.00 WIB. 😊", "username": ""}],
        }
        req = urllib.request.Request(f"{BASE}/public/schedule", data=json.dumps(payload).encode(), headers={**HEADERS, "Content-Type": "application/json"})
        try:
            with urllib.request.urlopen(req, timeout=30) as r:
                res = json.load(r)
            ok += 1
            print(f"  ✅ {slot.strftime('%d/%m %H:00')} WIB | {kind:5s} | {fn}")
            st.setdefault("posted", []).append(fn)
            with open(STATE, "w") as f:
                json.dump(st, f, indent=1, ensure_ascii=False)
        except Exception as e:
            fail += 1
            print(f"  ❌ {fn}: {e}")
    print(f"\n📊 Total: {ok} OK, {fail} gagal")

if __name__ == "__main__":
    main()
