#!/usr/bin/env python3
"""StudioSoft IG Story — Sesi 2, 29 Juni 2026 (16:00 WIB)
Overlay: PUTIH 80% (sesi 2 hari ini)
Topik: random dari pool
"""

from PIL import Image, ImageDraw, ImageFont, ImageFilter
import base64, json, os, random, urllib.request, io, textwrap, urllib.parse

# ===== CREDENTIALS =====
REPLIZ_AUTH = "NDY1NDYwOTg2Njpzb09vSDJJUnk2QmthSXJIU0FmMW5HbHkyUmNvaXc5Wg=="
WP_AUTH = base64.b64encode(b"bambangbot:qWYh MWiu BJL0 O6UI vxbt 11Ds").decode()
WP_UPLOAD_URL = "http://103.175.217.138/wp-json/wp/v2/media"
REPLIZ_URL = "https://api.repliz.com/public/schedule"
FONT_DIR = os.path.expanduser("~/.fonts")
W, H = 1080, 1920

# ===== TOPIK POOL (tema acak, gak boleh sama — kita pilih 1) =====
TOPICS = [
    {
        "title": "SEO Bikin Bisnismu\nMuncul di Google",
        "body": "Bayangin tiap hari ada puluhan orang nyari\n"
                 "layanan kayak bisnismu — tapi mereka nemuin\n"
                 "kompetitor, bukan kamu.\n\n"
                 "Itulah gunanya SEO. Bikin websitemu\n"
                 "ramah Google, naik peringkat, dapet\n"
                 "trafik gratis tiap hari.\n\n"
                 "KONSULTASI GRATIS SEKARANG!"
    },
    {
        "title": "Social Media\nBukan Sekadar Posting",
        "body": "Banyak yang kira sosmed cukup upload foto\n"
                 "terus ditunggu rejeki nomplok.\n\n"
                 "Padahal ada strateginya: konten plan,\n"
                 "copywriting, engagement, iklan — semua\n"
                 "harus nyambung.\n\n"
                 "Nggak perlu bingung sendiri.\n\n"
                 "KONSULTASI GRATIS SEKARANG!"
    },
    {
        "title": "Digital Marketing\nBukan Buang Duit",
        "body": "Pernah pasang iklan Facebook tapi\n"
                 "nggak ada hasil? Mungkin strateginya\n"
                 "yang perlu diotak-atik.\n\n"
                 "Digital marketing itu soal tepat sasaran,\n"
                 "bukan soal besar budget.\n\n"
                 "Biar iklanmu menghasilkan, bukan\n"
                 "sekadar jadi pengeluaran.\n\n"
                 "KONSULTASI GRATIS SEKARANG!"
    },
    {
        "title": "AI untuk\nBisnis Kamu",
        "body": "AI bukan cuma buat bikin gambar lucu.\n"
                 "Sekarang AI bisa bantu riset pasar,\n"
                 "nulis konten, analisis data, sampai\n"
                 "jawab pertanyaan pelanggan 24 jam.\n\n"
                 "Bisnis kecil pun bisa main AI —\n"
                 "tinggal tahu cara pakainya.\n\n"
                 "KONSULTASI GRATIS SEKARANG!"
    },
    {
        "title": "Content Marketing\nItu Investasi",
        "body": "Konten yang bagus bukan cuma\n"
                 "sekadar hiasan website.\n\n"
                 "Dia kerja 24/7: narik pengunjung,\n"
                 "bangun kepercayaan, bikin orang\n"
                 "yakin pilih bisnismu.\n\n"
                 "Satu artikel bagus bisa kasih\n"
                 "traffic bertahun-tahun.\n\n"
                 "KONSULTASI GRATIS SEKARANG!"
    },
    {
        "title": "Branding:\nLebih dari Sekadar Logo",
        "body": "Branding itu soal gimana orang\n"
                 "ngebranding kamu, bukan caramu\n"
                 "ngebranding diri sendiri.\n\n"
                 "Dari warna, tone bicara, sampai\n"
                 "cara customer service melayani —\n"
                 "semuanya branding.\n\n"
                 "Biar bisnismu diingat, bukan\n"
                 "sekadar dilihat.\n\n"
                 "KONSULTASI GRATIS SEKARANG!"
    },
]

random.seed()

# Pilih random topic
topic_idx = random.randint(0, len(TOPICS) - 1)
topic = TOPICS[topic_idx]
topic_names = ["SEO", "Social Media", "Digital Marketing", "AI", "Content Marketing", "Branding"]
chosen_topic_name = topic_names[topic_idx]

print(f"🎯 Topik terpilih: {chosen_topic_name}")

# ===== DOWNLOAD BACKGROUND DARI PEXELS =====
# Cari keyword random dari topic
pexels_keywords = {
    "SEO": ["digital marketing laptop", "seo strategy", "website analytics"],
    "Social Media": ["social media marketing", "instagram content"],
    "Digital Marketing": ["digital marketing strategy", "marketing laptop"],
    "AI": ["artificial intelligence", "AI technology"],
    "Content Marketing": ["content creator", "writing content laptop"],
    "Branding": ["branding design", "brand strategy"],
}
kw = random.choice(pexels_keywords[chosen_topic_name])

print(f"📷 Membuat background elegan...")

# Use a soft gradient background (no API dependency)
bg = Image.new("RGB", (W, H), (240, 240, 245))
from PIL import ImageDraw as IDraw
grad = IDraw.Draw(bg)
for y in range(H//2):
    r = int(240 + (220 - 240) * y / (H//2))
    g = int(240 + (228 - 240) * y / (H//2))
    b = int(248 + (238 - 248) * y / (H//2))
    grad.line([(0, y), (W, y)], fill=(r, g, b))
for y in range(H//2, H):
    progress = (y - H//2) / (H//2)
    r = int(220 + (240 - 220) * progress)
    g = int(228 + (240 - 228) * progress)
    b = int(238 + (248 - 238) * progress)
    grad.line([(0, y), (W, y)], fill=(r, g, b))

# ===== OVERLAY: PUTIH 80% =====
overlay = Image.new("RGBA", (W, H), (255, 255, 255, int(255 * 0.80)))
bg = bg.convert("RGBA")
bg = Image.alpha_composite(bg, overlay)
bg = bg.convert("RGB")

# ===== DRAW =====
draw = ImageDraw.Draw(bg)

# Fonts
font_title = ImageFont.truetype(os.path.join(FONT_DIR, "Poppins-Bold.ttf"), 70)
font_body = ImageFont.truetype(os.path.join(FONT_DIR, "Poppins-Regular.ttf"), 43)

# Color for text on white overlay = dark gray / black
text_color = (30, 30, 30)

# ===== TITLE — center middle-ish =====
title = topic["title"]
body = topic["body"]

# Manual line splitting since we have \n in strings
title_lines = title.split("\n")

# Calculate total height of title
total_title_h = 0
for line in title_lines:
    bbox = draw.textbbox((0, 0), line, font=font_title)
    th = bbox[3] - bbox[1]
    total_title_h += th + 10

# Start title at ~30% from top
title_y_start = int(H * 0.22)

cy = title_y_start
for line in title_lines:
    bbox = draw.textbbox((0, 0), line, font=font_title)
    tw = bbox[2] - bbox[0]
    th = bbox[3] - bbox[1]
    x = (W - tw) // 2
    draw.text((x, cy), line, font=font_title, fill=text_color)
    cy += th + 10

# ===== BODY =====
body_lines = body.split("\n")
# Add some space before body
cy += 60

for line in body_lines:
    bbox = draw.textbbox((0, 0), line, font=font_body)
    tw = bbox[2] - bbox[0]
    th = bbox[3] - bbox[1]
    x = (W - tw) // 2
    draw.text((x, cy), line, font=font_body, fill=text_color)
    cy += th + 8

# ===== FOOTER =====
# Create footer with centered text logo '#StudioSoft' style and www.studiosoft.id
# Since logo download may fail, let's try a known working URL or make a text logo
logo_url = "https://studiosoft.id/wp-content/uploads/2025/10/Digital-Marketing-Agency-Surabaya-StudioSoft-1.png"
logged_in = False

try:
    # Try getting logo from WP media via API
    wp_media_req = urllib.request.Request(
        "http://103.175.217.138/wp-json/wp/v2/media?search=logo&per_page=5",
        headers={
            "Authorization": f"Basic {WP_AUTH}",
            "Host": "studiosoft.id",
        }
    )
    with urllib.request.urlopen(wp_media_req, timeout=10) as r:
        media_list = json.loads(r.read())
    # Find a logo (smallest image that looks like a logo)
    logo_img_url = None
    for m in media_list:
        src = m.get("source_url", "")
        if src and ("logo" in src.lower() or "cropped" in src.lower()):
            logo_img_url = src
            break
    if not logo_img_url and media_list:
        # Use first media
        logo_img_url = media_list[0].get("source_url", "")
    
    if logo_img_url:
        print(f"  Logo URL: {logo_img_url}")
        urllib.request.urlretrieve(logo_img_url, "/tmp/studiosoft_logo.png")
        logo = Image.open("/tmp/studiosoft_logo.png").convert("RGBA")

        logo_w, logo_h = logo.size
        logo_new_h = 150
        logo_new_w = int(logo_w * logo_new_h / logo_h)
        if logo_new_w > W - 100:
            logo_new_w = W - 100
            logo_new_h = int(logo_h * logo_new_w / logo_w)
        logo = logo.resize((logo_new_w, logo_new_h), Image.LANCZOS)

        logo_x = (W - logo_new_w) // 2
        logo_y = H - 100 - logo_new_h
        bg.paste(logo, (logo_x, logo_y), logo)
        logged_in = True
        print(f"  Logo pasted at y={logo_y}")
except Exception as e:
    print(f"  Logo from WP failed: {e}, using text logo")

if not logged_in:
    # Try direct logo URLs
    for try_url in [
        "https://studiosoft.id/wp-content/uploads/2025/10/cropped-Digital-Marketing-Agency-Surabaya-StudioSoft-1-1.png",
        "https://studiosoft.id/wp-content/uploads/2025/10/Digital-Marketing-Agency-Surabaya-StudioSoft-1.png",
    ]:
        try:
            urllib.request.urlretrieve(try_url, "/tmp/studiosoft_logo.png")
            logo = Image.open("/tmp/studiosoft_logo.png").convert("RGBA")
            logo_w, logo_h = logo.size
            logo_new_h = 150
            logo_new_w = int(logo_w * logo_new_h / logo_h)
            if logo_new_w > W - 100:
                logo_new_w = W - 100
                logo_new_h = int(logo_h * logo_new_w / logo_w)
            logo = logo.resize((logo_new_w, logo_new_h), Image.LANCZOS)
            logo_x = (W - logo_new_w) // 2
            logo_y = H - 100 - logo_new_h
            bg.paste(logo, (logo_x, logo_y), logo)
            logged_in = True
            print(f"  Logo downloaded directly, pasted at y={logo_y}")
            break
        except:
            pass

# Footer text below logo
font_footer = ImageFont.truetype(os.path.join(FONT_DIR, "Poppins-Regular.ttf"), 32)
footer_text = "www.studiosoft.id"

if logged_in:
    fy = H - 100 - 150 + 150 + 15  # logo_y + logo_new_h + 15
else:
    fy = H - 100
    # Draw a simple text-based logo "STUDIOSOFT"
    font_logo_text = ImageFont.truetype(os.path.join(FONT_DIR, "Poppins-Bold.ttf"), 55)
    logo_text = "STUDIOSOFT"
    bbox = draw.textbbox((0, 0), logo_text, font=font_logo_text)
    lw = bbox[2] - bbox[0]
    draw.text(((W - lw) // 2, H - 160), logo_text, font=font_logo_text, fill=text_color)
    fy = H - 100

bbox = draw.textbbox((0, 0), footer_text, font=font_footer)
fw = bbox[2] - bbox[0]
draw.text(((W - fw) // 2, fy), footer_text, font=font_footer, fill=text_color)

# ===== SAVE =====
out_path = "/tmp/studiosoft_story_sesi2_29jun.png"
bg.save(out_path)
print(f"\n✅ Gambar tersimpan: {out_path}")

# ===== UPLOAD KE SERVER OPENCLAW (FIX 21/08) =====
print(f"\n📤 Upload ke server OpenClaw...")
source_url = upload_image_to_server(out_path)
print(f"  ✅ URL: {source_url}")

if not source_url:
    print("❌ Gagal upload — batal schedule")
    exit(1)

# ===== SCHEDULE VIA REPLIZ =====
# Sesi 2: 16:00 WIB. Now 16:10 WIB. Schedule 30 menit lagi = 16:40 WIB
from datetime import datetime, timezone, timedelta
now_utc = datetime.now(timezone.utc)
schedule_utc = now_utc + timedelta(minutes=30)
schedule_str = schedule_utc.strftime("%Y-%m-%dT%H:%M:%S.000Z")
schedule_wib = schedule_utc + timedelta(hours=7)
schedule_wib_str = schedule_wib.strftime("%H:%M WIB")

print(f"\n📅 Schedule: {schedule_str} UTC ({schedule_wib_str})")

# IG Story
ig_payload = {
    "accountId": "6a38ac33c5ff4ce3a3231232",  # StudioSoft IG
    "scheduleAt": schedule_str,
    "type": "story",
    "medias": [{"url": source_url, "type": "image"}]
}

ig_headers = {
    "Authorization": f"Basic {REPLIZ_AUTH}",
    "Content-Type": "application/json"
}

# Schedule IG
print(f"📱 Schedule IG Story...")
ig_req = urllib.request.Request(
    REPLIZ_URL,
    data=json.dumps(ig_payload).encode(),
    headers=ig_headers,
    method="POST"
)
try:
    with urllib.request.urlopen(ig_req) as r:
        ig_resp = json.loads(r.read())
    ig_schedule_id = ig_resp.get("scheduleId", "?")
    print(f"  ✅ IG Schedule ID: {ig_schedule_id}")
except urllib.error.HTTPError as e:
    print(f"  ❌ IG Schedule gagal: {e.code} {e.read().decode()}")
    ig_schedule_id = None

# Schedule FB Story
fb_payload = {
    "accountId": "6a334952c5ff4ce3a3225941",  # FB StudioSoft
    "scheduleAt": schedule_str,
    "type": "story",
    "medias": [{"url": source_url, "type": "image"}]
}

print(f"📘 Schedule FB Story...")
fb_req = urllib.request.Request(
    REPLIZ_URL,
    data=json.dumps(fb_payload).encode(),
    headers=ig_headers,
    method="POST"
)
try:
    with urllib.request.urlopen(fb_req) as r:
        fb_resp = json.loads(r.read())
    fb_schedule_id = fb_resp.get("scheduleId", "?")
    print(f"  ✅ FB Schedule ID: {fb_schedule_id}")
except urllib.error.HTTPError as e:
    print(f"  ❌ FB Schedule gagal: {e.code} {e.read().decode()}")
    fb_schedule_id = None

# ===== RINGKASAN =====
print(f"\n{'='*60}")
print(f"📊 RINGKASAN STUDIOSOFT IG STORY — SESI 2")
print(f"{'='*60}")
print(f"  Tanggal   : 29 Juni 2026")
print(f"  Sesi      : 2 (16:00 WIB)")
print(f"  Warna     : PUTIH (80%)")
print(f"  Topik     : {chosen_topic_name}")
print(f"  Schedule  : {schedule_wib_str}")
print(f"  IG ID     : {ig_schedule_id or '❌'}")
print(f"  FB ID     : {fb_schedule_id or '❌'}")
print(f"  Image URL : {source_url}")
print(f"{'='*60}")

# Simpan state
from datetime import date

from repliz_client import upload_image_to_server, AUTH_BASE64 as REPLIZ_AUTH
WP_AUTH = base64.b64encode(b"bambangbot:qWYh MWiu BJL0 O6UI vxbt 11Ds").decode()
WP_UPLOAD_URL = "http://103.175.217.138/wp-json/wp/v2/media"
REPLIZ_URL = "https://api.repliz.com/public/schedule"
FONT_DIR = os.path.expanduser("~/.fonts")
W, H = 1080, 1920

# ===== TOPIK POOL (tema acak, gak boleh sama — kita pilih 1) =====
TOPICS = [
    {
        "title": "SEO Bikin Bisnismu\nMuncul di Google",
        "body": "Bayangin tiap hari ada puluhan orang nyari\n"
                 "layanan kayak bisnismu — tapi mereka nemuin\n"
                 "kompetitor, bukan kamu.\n\n"
                 "Itulah gunanya SEO. Bikin websitemu\n"
                 "ramah Google, naik peringkat, dapet\n"
                 "trafik gratis tiap hari.\n\n"
                 "KONSULTASI GRATIS SEKARANG!"
    },
    {
        "title": "Social Media\nBukan Sekadar Posting",
        "body": "Banyak yang kira sosmed cukup upload foto\n"
                 "terus ditunggu rejeki nomplok.\n\n"
                 "Padahal ada strateginya: konten plan,\n"
                 "copywriting, engagement, iklan — semua\n"
                 "harus nyambung.\n\n"
                 "Nggak perlu bingung sendiri.\n\n"
                 "KONSULTASI GRATIS SEKARANG!"
    },
    {
        "title": "Digital Marketing\nBukan Buang Duit",
        "body": "Pernah pasang iklan Facebook tapi\n"
                 "nggak ada hasil? Mungkin strateginya\n"
                 "yang perlu diotak-atik.\n\n"
                 "Digital marketing itu soal tepat sasaran,\n"
                 "bukan soal besar budget.\n\n"
                 "Biar iklanmu menghasilkan, bukan\n"
                 "sekadar jadi pengeluaran.\n\n"
                 "KONSULTASI GRATIS SEKARANG!"
    },
    {
        "title": "AI untuk\nBisnis Kamu",
        "body": "AI bukan cuma buat bikin gambar lucu.\n"
                 "Sekarang AI bisa bantu riset pasar,\n"
                 "nulis konten, analisis data, sampai\n"
                 "jawab pertanyaan pelanggan 24 jam.\n\n"
                 "Bisnis kecil pun bisa main AI —\n"
                 "tinggal tahu cara pakainya.\n\n"
                 "KONSULTASI GRATIS SEKARANG!"
    },
    {
        "title": "Content Marketing\nItu Investasi",
        "body": "Konten yang bagus bukan cuma\n"
                 "sekadar hiasan website.\n\n"
                 "Dia kerja 24/7: narik pengunjung,\n"
                 "bangun kepercayaan, bikin orang\n"
                 "yakin pilih bisnismu.\n\n"
                 "Satu artikel bagus bisa kasih\n"
                 "traffic bertahun-tahun.\n\n"
                 "KONSULTASI GRATIS SEKARANG!"
    },
    {
        "title": "Branding:\nLebih dari Sekadar Logo",
        "body": "Branding itu soal gimana orang\n"
                 "ngebranding kamu, bukan caramu\n"
                 "ngebranding diri sendiri.\n\n"
                 "Dari warna, tone bicara, sampai\n"
                 "cara customer service melayani —\n"
                 "semuanya branding.\n\n"
                 "Biar bisnismu diingat, bukan\n"
                 "sekadar dilihat.\n\n"
                 "KONSULTASI GRATIS SEKARANG!"
    },
]

random.seed()

# Pilih random topic
topic_idx = random.randint(0, len(TOPICS) - 1)
topic = TOPICS[topic_idx]
topic_names = ["SEO", "Social Media", "Digital Marketing", "AI", "Content Marketing", "Branding"]
chosen_topic_name = topic_names[topic_idx]

print(f"🎯 Topik terpilih: {chosen_topic_name}")

# ===== DOWNLOAD BACKGROUND DARI PEXELS =====
# Cari keyword random dari topic
pexels_keywords = {
    "SEO": ["digital marketing laptop", "seo strategy", "website analytics"],
    "Social Media": ["social media marketing", "instagram content"],
    "Digital Marketing": ["digital marketing strategy", "marketing laptop"],
    "AI": ["artificial intelligence", "AI technology"],
    "Content Marketing": ["content creator", "writing content laptop"],
    "Branding": ["branding design", "brand strategy"],
}
kw = random.choice(pexels_keywords[chosen_topic_name])

print(f"📷 Membuat background elegan...")

# Use a soft gradient background (no API dependency)
bg = Image.new("RGB", (W, H), (240, 240, 245))
from PIL import ImageDraw as IDraw
grad = IDraw.Draw(bg)
for y in range(H//2):
    r = int(240 + (220 - 240) * y / (H//2))
    g = int(240 + (228 - 240) * y / (H//2))
    b = int(248 + (238 - 248) * y / (H//2))
    grad.line([(0, y), (W, y)], fill=(r, g, b))
for y in range(H//2, H):
    progress = (y - H//2) / (H//2)
    r = int(220 + (240 - 220) * progress)
    g = int(228 + (240 - 228) * progress)
    b = int(238 + (248 - 238) * progress)
    grad.line([(0, y), (W, y)], fill=(r, g, b))

# ===== OVERLAY: PUTIH 80% =====
overlay = Image.new("RGBA", (W, H), (255, 255, 255, int(255 * 0.80)))
bg = bg.convert("RGBA")
bg = Image.alpha_composite(bg, overlay)
bg = bg.convert("RGB")

# ===== DRAW =====
draw = ImageDraw.Draw(bg)

# Fonts
font_title = ImageFont.truetype(os.path.join(FONT_DIR, "Poppins-Bold.ttf"), 70)
font_body = ImageFont.truetype(os.path.join(FONT_DIR, "Poppins-Regular.ttf"), 43)

# Color for text on white overlay = dark gray / black
text_color = (30, 30, 30)

# ===== TITLE — center middle-ish =====
title = topic["title"]
body = topic["body"]

# Manual line splitting since we have \n in strings
title_lines = title.split("\n")

# Calculate total height of title
total_title_h = 0
for line in title_lines:
    bbox = draw.textbbox((0, 0), line, font=font_title)
    th = bbox[3] - bbox[1]
    total_title_h += th + 10

# Start title at ~30% from top
title_y_start = int(H * 0.22)

cy = title_y_start
for line in title_lines:
    bbox = draw.textbbox((0, 0), line, font=font_title)
    tw = bbox[2] - bbox[0]
    th = bbox[3] - bbox[1]
    x = (W - tw) // 2
    draw.text((x, cy), line, font=font_title, fill=text_color)
    cy += th + 10

# ===== BODY =====
body_lines = body.split("\n")
# Add some space before body
cy += 60

for line in body_lines:
    bbox = draw.textbbox((0, 0), line, font=font_body)
    tw = bbox[2] - bbox[0]
    th = bbox[3] - bbox[1]
    x = (W - tw) // 2
    draw.text((x, cy), line, font=font_body, fill=text_color)
    cy += th + 8

# ===== FOOTER =====
# Create footer with centered text logo '#StudioSoft' style and www.studiosoft.id
# Since logo download may fail, let's try a known working URL or make a text logo
logo_url = "https://studiosoft.id/wp-content/uploads/2025/10/Digital-Marketing-Agency-Surabaya-StudioSoft-1.png"
logged_in = False

try:
    # Try getting logo from WP media via API
    wp_media_req = urllib.request.Request(
        "http://103.175.217.138/wp-json/wp/v2/media?search=logo&per_page=5",
        headers={
            "Authorization": f"Basic {WP_AUTH}",
            "Host": "studiosoft.id",
        }
    )
    with urllib.request.urlopen(wp_media_req, timeout=10) as r:
        media_list = json.loads(r.read())
    # Find a logo (smallest image that looks like a logo)
    logo_img_url = None
    for m in media_list:
        src = m.get("source_url", "")
        if src and ("logo" in src.lower() or "cropped" in src.lower()):
            logo_img_url = src
            break
    if not logo_img_url and media_list:
        # Use first media
        logo_img_url = media_list[0].get("source_url", "")
    
    if logo_img_url:
        print(f"  Logo URL: {logo_img_url}")
        urllib.request.urlretrieve(logo_img_url, "/tmp/studiosoft_logo.png")
        logo = Image.open("/tmp/studiosoft_logo.png").convert("RGBA")

        logo_w, logo_h = logo.size
        logo_new_h = 150
        logo_new_w = int(logo_w * logo_new_h / logo_h)
        if logo_new_w > W - 100:
            logo_new_w = W - 100
            logo_new_h = int(logo_h * logo_new_w / logo_w)
        logo = logo.resize((logo_new_w, logo_new_h), Image.LANCZOS)

        logo_x = (W - logo_new_w) // 2
        logo_y = H - 100 - logo_new_h
        bg.paste(logo, (logo_x, logo_y), logo)
        logged_in = True
        print(f"  Logo pasted at y={logo_y}")
except Exception as e:
    print(f"  Logo from WP failed: {e}, using text logo")

if not logged_in:
    # Try direct logo URLs
    for try_url in [
        "https://studiosoft.id/wp-content/uploads/2025/10/cropped-Digital-Marketing-Agency-Surabaya-StudioSoft-1-1.png",
        "https://studiosoft.id/wp-content/uploads/2025/10/Digital-Marketing-Agency-Surabaya-StudioSoft-1.png",
    ]:
        try:
            urllib.request.urlretrieve(try_url, "/tmp/studiosoft_logo.png")
            logo = Image.open("/tmp/studiosoft_logo.png").convert("RGBA")
            logo_w, logo_h = logo.size
            logo_new_h = 150
            logo_new_w = int(logo_w * logo_new_h / logo_h)
            if logo_new_w > W - 100:
                logo_new_w = W - 100
                logo_new_h = int(logo_h * logo_new_w / logo_w)
            logo = logo.resize((logo_new_w, logo_new_h), Image.LANCZOS)
            logo_x = (W - logo_new_w) // 2
            logo_y = H - 100 - logo_new_h
            bg.paste(logo, (logo_x, logo_y), logo)
            logged_in = True
            print(f"  Logo downloaded directly, pasted at y={logo_y}")
            break
        except:
            pass

# Footer text below logo
font_footer = ImageFont.truetype(os.path.join(FONT_DIR, "Poppins-Regular.ttf"), 32)
footer_text = "www.studiosoft.id"

if logged_in:
    fy = H - 100 - 150 + 150 + 15  # logo_y + logo_new_h + 15
else:
    fy = H - 100
    # Draw a simple text-based logo "STUDIOSOFT"
    font_logo_text = ImageFont.truetype(os.path.join(FONT_DIR, "Poppins-Bold.ttf"), 55)
    logo_text = "STUDIOSOFT"
    bbox = draw.textbbox((0, 0), logo_text, font=font_logo_text)
    lw = bbox[2] - bbox[0]
    draw.text(((W - lw) // 2, H - 160), logo_text, font=font_logo_text, fill=text_color)
    fy = H - 100

bbox = draw.textbbox((0, 0), footer_text, font=font_footer)
fw = bbox[2] - bbox[0]
draw.text(((W - fw) // 2, fy), footer_text, font=font_footer, fill=text_color)

# ===== SAVE =====
out_path = "/tmp/studiosoft_story_sesi2_29jun.png"
bg.save(out_path)
print(f"\n✅ Gambar tersimpan: {out_path}")

# ===== UPLOAD KE SERVER OPENCLAW (FIX 21/08) =====
print(f"\n📤 Upload ke server OpenClaw...")
source_url = upload_image_to_server(out_path)
print(f"  ✅ URL: {source_url}")

if not source_url:
    print("❌ Gagal upload — batal schedule")
    exit(1)

# ===== SCHEDULE VIA REPLIZ =====
# Sesi 2: 16:00 WIB. Now 16:10 WIB. Schedule 30 menit lagi = 16:40 WIB
from datetime import datetime, timezone, timedelta
now_utc = datetime.now(timezone.utc)
schedule_utc = now_utc + timedelta(minutes=30)
schedule_str = schedule_utc.strftime("%Y-%m-%dT%H:%M:%S.000Z")
schedule_wib = schedule_utc + timedelta(hours=7)
schedule_wib_str = schedule_wib.strftime("%H:%M WIB")

print(f"\n📅 Schedule: {schedule_str} UTC ({schedule_wib_str})")

# IG Story
ig_payload = {
    "accountId": "6a38ac33c5ff4ce3a3231232",  # StudioSoft IG
    "scheduleAt": schedule_str,
    "type": "story",
    "medias": [{"url": source_url, "type": "image"}]
}

ig_headers = {
    "Authorization": f"Basic {REPLIZ_AUTH}",
    "Content-Type": "application/json"
}

# Schedule IG
print(f"📱 Schedule IG Story...")
ig_req = urllib.request.Request(
    REPLIZ_URL,
    data=json.dumps(ig_payload).encode(),
    headers=ig_headers,
    method="POST"
)
try:
    with urllib.request.urlopen(ig_req) as r:
        ig_resp = json.loads(r.read())
    ig_schedule_id = ig_resp.get("scheduleId", "?")
    print(f"  ✅ IG Schedule ID: {ig_schedule_id}")
except urllib.error.HTTPError as e:
    print(f"  ❌ IG Schedule gagal: {e.code} {e.read().decode()}")
    ig_schedule_id = None

# Schedule FB Story
fb_payload = {
    "accountId": "6a334952c5ff4ce3a3225941",  # FB StudioSoft
    "scheduleAt": schedule_str,
    "type": "story",
    "medias": [{"url": source_url, "type": "image"}]
}

print(f"📘 Schedule FB Story...")
fb_req = urllib.request.Request(
    REPLIZ_URL,
    data=json.dumps(fb_payload).encode(),
    headers=ig_headers,
    method="POST"
)
try:
    with urllib.request.urlopen(fb_req) as r:
        fb_resp = json.loads(r.read())
    fb_schedule_id = fb_resp.get("scheduleId", "?")
    print(f"  ✅ FB Schedule ID: {fb_schedule_id}")
except urllib.error.HTTPError as e:
    print(f"  ❌ FB Schedule gagal: {e.code} {e.read().decode()}")
    fb_schedule_id = None

# ===== RINGKASAN =====
print(f"\n{'='*60}")
print(f"📊 RINGKASAN STUDIOSOFT IG STORY — SESI 2")
print(f"{'='*60}")
print(f"  Tanggal   : 29 Juni 2026")
print(f"  Sesi      : 2 (16:00 WIB)")
print(f"  Warna     : PUTIH (80%)")
print(f"  Topik     : {chosen_topic_name}")
print(f"  Schedule  : {schedule_wib_str}")
print(f"  IG ID     : {ig_schedule_id or '❌'}")
print(f"  FB ID     : {fb_schedule_id or '❌'}")
print(f"  Image URL : {source_url}")
print(f"{'='*60}")

# Simpan state
from datetime import date
today = date.today().isoformat()
state = {
    "date": today,
    "sesi": 2,
    "warna": "PUTIH",
    "opacity": "80%",
    "topik": chosen_topic_name,
    "ig_schedule_id": ig_schedule_id,
    "fb_schedule_id": fb_schedule_id,
    "image_url": source_url,
    "schedule_at": schedule_str
}

state_dir = os.path.expanduser("~/.openclaw/workspace-atun/memory")
os.makedirs(state_dir, exist_ok=True)
with open(os.path.join(state_dir, f"studiosoft_ig_story_{today}_sesi2.json"), "w") as f:
    json.dump(state, f, indent=2)
print(f"\n  State tersimpan di memory/studiosoft_ig_story_{today}_sesi2.json")

