#!/usr/bin/env python3
"""
StudioSoft Healthcare Carousel Poster — Data Analytics RS
Post carousel ke Threads + LinkedIn + FB di slot 05:00 WIB
"""
import json, base64, os
from datetime import datetime, timezone, timedelta
from repliz_client import ReplizClient

client = ReplizClient()

# === ACCOUNTS ===
ACC_THREADS  = "6a335b9ec5ff4ce3a3225c2a"  # StudioSoft Threads
ACC_LINKEDIN = "6a334c49c5ff4ce3a32259c9"  # StudioSoft LinkedIn
ACC_FB       = "6a334952c5ff4ce3a3225941"  # StudioSoft FB

# === SLOT ===
WIB = timezone(timedelta(hours=7))
SLOT_HOUR = 5  # 05:00 WIB

# === CAROUSEL IMAGES ===
CAROUSEL_DIR = os.path.expanduser("~/.openclaw/workspace-atun/studiosoft_healthcare_analytics")

def encode_slides():
    """Encode all 5 carousel slides to base64 data URIs."""
    slide_files = [
        "01_cover.png",
        "02_mengapa.png",
        "03_insight.png",
        "04_langkah.png",
        "05_cta.png",
    ]
    slides = []
    for fname in slide_files:
        path = os.path.join(CAROUSEL_DIR, fname)
        img_url = upload_image_to_server(path)
        # FIX 21/08: no base64 — image via server OpenClaw
        slides.append({"url": img_url, "type": "image", "alt": fname})
    return slides

def make_schedule_at(wib_hour, wib_minute=0):
    """Convert WIB time to ISO UTC for scheduleAt."""
    now_wib = datetime.now(WIB)
    target = now_wib.replace(hour=wib_hour, minute=wib_minute, second=0, microsecond=0)
    # If the target time has already passed today, schedule for next day same time
    if target <= now_wib:
        target += timedelta(days=1)
    target_utc = target.astimezone(timezone.utc)
    return target_utc.strftime("%Y-%m-%dT%H:%M:%S.000Z")

def make_media_slot(wib_hour, minute_offset=0):
    """Return ISO UTC for album post at the slot."""
    return make_schedule_at(wib_hour, minute_offset)

def build_album(account_id, description, slides, schedule_at, topic=""):
    """Build album payload."""
    return {
        "accountId": account_id,
        "title": "",
        "description": description,
        "topic": topic,
        "type": "album",
        "medias": slides,
        "meta": {"title": "", "description": "", "url": ""},
        "additionalInfo": {
            "isAiGenerated": False, "isDraft": False,
            "collaborators": [], "mentions": [],
            "music": {"id": "", "artist": "", "name": "", "thumbnail": ""},
            "products": [], "tags": []
        },
        "replies": [],
        "scheduleAt": schedule_at,
    }

def build_reply(account_id, description, parent_id, schedule_at):
    """Build reply payload."""
    return {
        "accountId": account_id,
        "title": "",
        "description": description,
        "topic": "",
        "type": "text",
        "medias": [],
        "meta": {"title": "", "description": "", "url": ""},
        "additionalInfo": {
            "isAiGenerated": False, "isDraft": False,
            "collaborators": [], "mentions": [],
            "music": {"id": "", "artist": "", "name": "", "thumbnail": ""},
            "products": [], "tags": []
        },
        "replies": [parent_id],
        "scheduleAt": schedule_at,
    }

# === CONTENT ===
ARTICLE_URL = "https://studiosoft.id/data-analytics-rumah-sakit-kebutuhan-pasien"

# Threads content (max 500 chars)
THREADS_CAPTION = "RS & klinik punya banyak data — dari pendaftaran, website, sosmed, sampai feedback pasien. Tapi jarang dianalisis.\n\nPadahal di data itu ada jawaban:\n- Layanan apa yang paling dicari?\n- Jam berapa booking tertinggi?\n- Siapa demografi pasien?\n- Apa yang paling dikeluhkan?\n\nData bicara — Anda tinggal mendengar."
THREADS_REPLY2 = f"Baca selengkapnya: {ARTICLE_URL}\n\nKonsultasi strategi data-driven RS & klinik:\nwww.studiosoft.id"
THREADS_REPLY3 = "#StudioSoft #DataAnalytics #HealthcareRS #RumahSakit #DigitalMarketing"

# LinkedIn content
LINKEDIN_CAPTION = "Rumah sakit dan klinik menghasilkan data setiap hari — namun sebagian besar tidak pernah dianalisis dengan baik.\n\nData analytics bisa menjawab pertanyaan paling penting:\n✅ Layanan apa yang paling dicari pasien?\n✅ Dari mana asal pasien?\n✅ Jam berapa booking tertinggi?\n✅ Konten apa yang paling engaging?\n✅ Berapa biaya per pasien baru dari marketing?\n\nStudi kasus nyata: RS di Surabaya menemukan 60% traffic website berasal dari pencarian \"biaya operasi katarak\". Setelah membuat halaman khusus, booking naik 35% dalam 2 bulan.\n\nData-driven decision making adalah masa depan marketing RS."
LINKEDIN_REPLY2 = f"Baca artikel lengkapnya di: {ARTICLE_URL}\n\nKonsultasi strategi data analytics untuk RS & klinik:\nwww.studiosoft.id"
LINKEDIN_REPLY3 = "#StudioSoft #DataAnalytics #HealthcareMarketing #RumahSakit #DigitalMarketing"

# Facebook content
FB_CAPTION = "RS dan klinik itu sebenarnya duduk di atas gunung data. Setiap hari ada data pendaftaran, kunjungan website, interaksi sosmed, feedback pasien. Tapi kebanyakan gak pernah digali.\n\nPadahal dari data itu Anda bisa tahu:\n✅ Layanan apa yang paling banyak dicari pasien\n✅ Jam berapa pasien paling sering booking\n✅ Dari mana asal pasien\n✅ Konten apa yang paling diminati\n✅ Apa keluhan paling umum\n\nIni yang disebut data-driven marketing — dan ini keahlian utama StudioSoft sebagai partner pertumbuhan bisnis berbasis data.\n\n📖 Baca selengkapnya: {ARTICLE_URL}"
FB_REPLY2 = "Ada pertanyaan seputar data analytics untuk RS & klinik? Tanya di kolom komentar! 👇"
FB_REPLY3 = "#StudioSoft #DataAnalytics #HealthcareRS #RumahSakit #DigitalMarketing"

# === RUN ===
def run():
    print("=" * 50)
    print("StudioSoft Healthcare Carousel — Data Analytics RS")
    print(f"Time (WIB): {datetime.now(WIB).strftime('%Y-%m-%d %H:%M')}")
    print()

    slides = encode_slides()
    print(f"✅ {len(slides)} carousel slides encoded")

    # Album at 05:00 WIB, replies at 05:01 and 05:02
    album_at = make_schedule_at(SLOT_HOUR, 0)
    reply2_at = make_schedule_at(SLOT_HOUR, 1)
    reply3_at = make_schedule_at(SLOT_HOUR, 2)

    print(f"\n📅 Schedule: {SLOT_HOUR:02d}:00 WIB (UTC: {album_at})")
    print()

    platform_results = {}

    # === THREADS ===
    print("📱 THREADS:")
    try:
        r1 = client.post("/public/schedule", build_album(ACC_THREADS, THREADS_CAPTION, slides, album_at))
        pid = r1["scheduleId"]
        print(f"  ✅ Album posted → {pid} | {SLOT_HOUR:02d}:00 WIB")

        r2 = client.post("/public/schedule", build_reply(ACC_THREADS, THREADS_REPLY2, pid, reply2_at))
        pid2 = r2["scheduleId"]
        print(f"  ✅ Reply 2 → {pid2} | {SLOT_HOUR:02d}:01 WIB")

        r3 = client.post("/public/schedule", build_reply(ACC_THREADS, THREADS_REPLY3, pid, reply3_at))
        pid3 = r3["scheduleId"]
        print(f"  ✅ Reply 3 → {pid3} | {SLOT_HOUR:02d}:02 WIB")

        platform_results["threads"] = True
    except Exception as e:
        print(f"  ❌ Threads failed: {e}")
        platform_results["threads"] = False

    # === LINKEDIN ===
    print("\n💼 LINKEDIN:")
    try:
        r1 = client.post("/public/schedule", build_album(ACC_LINKEDIN, LINKEDIN_CAPTION, slides, album_at))
        pid = r1["scheduleId"]
        print(f"  ✅ Album posted → {pid} | {SLOT_HOUR:02d}:00 WIB")

        r2 = client.post("/public/schedule", build_reply(ACC_LINKEDIN, LINKEDIN_REPLY2, pid, reply2_at))
        pid2 = r2["scheduleId"]
        print(f"  ✅ Reply 2 → {pid2} | {SLOT_HOUR:02d}:01 WIB")

        r3 = client.post("/public/schedule", build_reply(ACC_LINKEDIN, LINKEDIN_REPLY3, pid, reply3_at))
        pid3 = r3["scheduleId"]
        print(f"  ✅ Reply 3 → {pid3} | {SLOT_HOUR:02d}:02 WIB")

        platform_results["linkedin"] = True
    except Exception as e:
        print(f"  ❌ LinkedIn failed: {e}")
        platform_results["linkedin"] = False

    # === FB ===
    print("\n🔵 FACEBOOK:")
    try:
        r1 = client.post("/public/schedule", build_album(ACC_FB, FB_CAPTION, slides, album_at))
        pid = r1["scheduleId"]
        print(f"  ✅ Album posted → {pid} | {SLOT_HOUR:02d}:00 WIB")

        r2 = client.post("/public/schedule", build_reply(ACC_FB, FB_REPLY2, pid, reply2_at))
        pid2 = r2["scheduleId"]
        print(f"  ✅ Reply 2 → {pid2} | {SLOT_HOUR:02d}:01 WIB")

        r3 = client.post("/public/schedule", build_reply(ACC_FB, FB_REPLY3, pid, reply3_at))
        pid3 = r3["scheduleId"]
        print(f"  ✅ Reply 3 → {pid3} | {SLOT_HOUR:02d}:02 WIB")

        platform_results["fb"] = True
    except Exception as e:
        print(f"  ❌ Facebook failed: {e}")
        platform_results["fb"] = False

    # === Summary ===
    print("\n" + "=" * 50)
    all_ok = all(platform_results.values())
    if all_ok:
        print("✅ Semua platform berhasil dijadwalkan!")
    else:
        failed = [k for k, v in platform_results.items() if not v]
        print(f"⚠️  Beberapa platform gagal: {', '.join(failed)}")

    # Update state
    state = {
        "index": 9,
        "topic": "Data Analytics RS",
        "last_post": datetime.now(WIB).strftime("%Y-%m-%d %H:%M")
    }
    state_file = os.path.expanduser("~/.openclaw/workspace-atun/studiosoft_healthcare_state.json")
    with open(state_file, "w") as f:
        json.dump(state, f)
    print(f"\n📝 State updated: index 9 → Data Analytics RS")
    print(f"📅 Next up: roll back to index 0 or reach end of 10")

    return all_ok


if __name__ == "__main__":
    success = run()
    exit(0 if success else 1)
