#!/usr/bin/env python3
"""
Twitter @ukyhandoko — posting carousel IG StudioSoft (SSIGSEP) yang sudah di-generate.
4 slide per album, caption ringkas, tanpa mention internal, slot kosong 05-23 WIB.
"""
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))
TW = "6a792f0a62caae1e04f57992"
SLOTS = [5, 8, 11, 14, 17, 20, 23]
IMG_BASE = "https://mantapserver.tail3947bb.ts.net/openclaw-img/"
STATE_FILE = "/home/mantapman/.hermes/profiles/atun/workspace/twitter_uky_carousel_state.json"

# Caption per topik carousel SSIGSEP (ringkas, pancing diskusi)
CAPS = {
    1: "SEO tidak mati, ia bertransformasi. Google sekarang 'berpikir' — RankBrain & MUM paham konteks, AI Overview rangkum jawaban langsung di atas pencarian.\n\nKonten dangkal tenggelam, brand kredibel naik. Cara kita menulis harus berubah — bukan cuma kata kuncinya.\n\nSetuju? Scroll slide-nya & kasih pendapatmu 👇",
    2: "10 tools AI terbaik 2026 bukan sekadar tren — ini senjata buat yang mau kerja lebih cepat dan lebih cerdas.\n\nYang menarik: tools yang sama bisa bikin hasil beda jauh, tergantung cara pakainya.\n\nPernah coba yang mana? Cerita di komen! 👇",
    3: "Google kini 'berpikir' — AI Overview merangkum jawaban langsung di atas hasil pencarian. Konsekuensinya: konten dangkal tenggelam, brand kredibel naik.\n\nYang perlu diubah: cara kita menulis, bukan cuma kata kuncinya.\n\nScroll slide-nya, setuju atau nggak? 👇",
}

def default_cap(n):
    return (
        f"Carousel StudioSoft hari ini — edisi #{n}. 📊\n\n"
        f"Poin-poin pentingnya udah dirangkum di slide. Baca sampai slide terakhir, terus kasih tau: bagian mana yang paling relate sama bisnismu?\n\n"
        f"Scroll & komen di bawah! 👇"
    )

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

def main():
    count = int(sys.argv[1]) if len(sys.argv) > 1 else 10
    st = load_state()
    used = set(st.get("posted", []))
    # ambil semua SSIGSEP di server (01-30)
    import os, re
    files = sorted(os.listdir("/home/mantapman/.hermes/profiles/atun/workspace/openclaw-img"))
    groups = {}
    for f in files:
        m = re.match(r"SSIGSEP_(\d+)_(\d+)\.jpg", f)
        if m:
            groups.setdefault(int(m.group(1)), []).append(f)
    # urutkan slide dalam tiap album
    album_nums = sorted(groups)
    avail = [n for n in album_nums if n not in used]
    print(f"📂 album SSIGSEP di server: {len(album_nums)} | sudah dipakai twitter: {len(used)} | tersedia: {len(avail)}")

    # pending twitter utk slot
    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") == TW and (d.get("status") or "").lower() == "pending":
                pend.append(d)
    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
    for n in avail[:count]:
        slides = sorted(groups[n])  # SSIGSEP_NN_01..04
        if len(slides) < 4:
            continue
        # cari slot kosong
        slot = None
        for _ in range(21):
            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 = CAPS.get(n, default_cap(n))
        medias = [{"url": IMG_BASE + s, "type": "image", "alt": s} for s in slides[:4]]
        payload = {
            "accountId": TW,
            "title": f"Uky — Carousel StudioSoft #{n:02d}",
            "description": cap,
            "topic": "Digital Marketing",
            "type": "album",
            "medias": medias,
            "scheduleAt": at,
            "replies": [
                {"text": "Slide mana yang paling menarik buat kamu? Nomornya tulis di komen ya! 👇", "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 | SSIGSEP_{n:02d} ({len(slides)} slide)")
            st["posted"].append(n)
            with open(STATE_FILE, "w") as f:
                json.dump(st, f, indent=1)
        except Exception as e:
            fail += 1
            print(f"  ❌ SSIGSEP_{n:02d}: {e}")
    print(f"\n📊 Total: {ok} OK, {fail} gagal")

if __name__ == "__main__":
    main()
