#!/usr/bin/env python3
"""
StudioSoft — Schedule 30 Hari Carousel IG (2–31 Agustus 2026) via Repliz
- Tiap hari 08:00 WIB
- Upload slide ke WP (URL jpg, BUKAN base64)
- Caption sesuai konten, menyayat, ajak interaksi
"""
import json, os, sys, time
from studiosoft_carousel_engine import (
    render_carousel, rows_body, text_block_body, R28, SB30, M, CONTENT_W,
)
from studiosoft_august_content import CONTENT
from repliz_client import ReplizClient, ACC

OUT_ROOT = os.path.expanduser("~/.openclaw/workspace-atun/studiosoft_august_carousels")
os.makedirs(OUT_ROOT, exist_ok=True)

c = ReplizClient()

def cta_body(cta):
    """Body CTA: desc (soft) + items (chk) + garis aksi (bold)."""
    def fn(d, t, y=None, count_only=False):
        h = 0
        desc_h = 0
        for ln in cta["desc"].split("\n"):
            desc_h += int(R28.getbbox(ln)[3] * 1.35)
        h += desc_h + 20
        for it in cta["items"]:
            h += int(R28.getbbox(it)[3] * 1.3)
        action = "Konsultasi gratis → www.studiosoft.id"
        h += 30 + int(SB30.getbbox(action)[3] * 1.3)
        if count_only:
            return h
        yy = y
        from studiosoft_carousel_engine import draw_block
        yy = draw_block(d, cta["desc"], M, yy, R28, t["soft"], CONTENT_W)
        yy += 15
        for it in cta["items"]:
            d.text((M, yy), it, font=R28, fill=t["ink"])
            yy += int(R28.getbbox(it)[3] * 1.3)
        yy += 20
        yy = draw_block(d, action, M, yy, SB30, t["ink"], CONTENT_W)
        return yy
    return fn

def build_pages(day):
    cover = day["cover"]
    pages = []
    # Slide 1 — Cover
    pages.append({
        "title": cover["title"],
        "body": text_block_body(cover["sub"], R28, "soft"),
        "footer_right": "Swipe →",
    })
    # Slide 2-4 — Isi
    for p in day["pages"]:
        pages.append({"title": p["title"], "rows": p["rows"]})
    # Slide 5 — CTA
    pages.append({"title": day["cta"]["title"], "body": cta_body(day["cta"])})
    return pages

def main():
    results = []
    for idx, day in enumerate(CONTENT):
        day_num = day["day"]
        theme = day["theme"]
        out_dir = os.path.join(OUT_ROOT, f"2026-08-{day_num:02d}_{theme}")
        print(f"\n=== {day_num} Agustus ({theme}) ===")
        paths = render_carousel(theme, build_pages(day), out_dir, prefix="slide")
        # Upload ke WP → URL jpg
        urls = []
        for p in paths:
            fn = f"ss_aug{day_num:02d}_{os.path.basename(p)}"
            u = c.upload_to_wp(p, filename=fn)
            if not u:
                print(f"  ❌ Gagal upload {p}")
                return
            urls.append(u)
            print(f"  ✅ {os.path.basename(p)} → {u}")
        # Schedule 08:00 WIB
        schedule_at = c.make_schedule(2026, 8, day_num, 8, 0, wib=True)
        medias = [{"url": u, "type": "image", "alt": f"aug{day_num}_{i+1}"} for i, u in enumerate(urls)]
        title = " ".join(day["cover"]["title"]).title()
        try:
            res = c.schedule_album(ACC.STUDIOSOFT_IG, day["caption"], schedule_at, medias, title=title)
            sid = res.get("scheduleId", "?")
            print(f"  ✅ Scheduled 08:00 WIB → {sid}")
            results.append({"day": day_num, "theme": theme, "scheduleId": sid, "scheduleAt": schedule_at, "title": title})
        except Exception as e:
            print(f"  ❌ Schedule gagal: {e}")
            results.append({"day": day_num, "error": str(e)})
        time.sleep(0.5)

    with open(os.path.join(OUT_ROOT, "schedule_log.json"), "w") as f:
        json.dump(results, f, indent=2)
    ok = sum(1 for r in results if "scheduleId" in r)
    print(f"\n📦 Selesai: {ok}/{len(results)} jadwal sukses. Log: schedule_log.json")

if __name__ == "__main__":
    main()
