#!/usr/bin/env python3
"""Post DMark Guerilla Marketing carousel ke Threads @ukyhandoko via Repliz API"""
import base64, json, os, sys
import urllib.request
from datetime import datetime, timezone, timedelta

from repliz_client import upload_image_to_server, HEADERS, BASE, ACC
ACCOUNT_ID = ACC.UKY_THREADS


DIR = "/home/mantapman/.hermes/profiles/atun/workspace/dmark_guerilla_out"
FILES = ["01_cover.png", "02_isi1.png", "03_isi2.png"]

# Jadwal: +5 menit dari sekarang biar cukup waktu
WIB = timezone(timedelta(hours=7))
now = datetime.now(WIB) + timedelta(minutes=5)
iso = now.strftime("%Y-%m-%dT%H:%M:00+07:00")

# Caption Threads max 500 karakter
caption = (
    "Guerilla Marketing: strategi kreatif yang bikin brand lo "
    "diperhatiin tanpa perlu budget gede. Efek kejut, viral, "
    "dan memorable — itu kuncinya.\n\n"
    "Kreativitas > Anggaran. Always. 🎯\n\n"
    "#GuerillaMarketing #BrandingKreatif #DMARK #MarketingStrategy"
)

print(f"📤 Preparing {len(FILES)} images for Threads...")

medias = []
for fname in FILES:
    fpath = os.path.join(DIR, fname)
    img_url = upload_image_to_server(fpath)
    # FIX 21/08: no base64 — image via server OpenClaw
    medias.append({
        "url": img_url,
        "type": "image",
        "alt": fname,
    })
    print(f"  ✅ {fname} prepared")

payload = {
    "title": "",
    "description": caption[:500],
    "topic": "Marketing",
    "type": "album",
    "medias": medias,
    "meta": {"title": "", "description": "", "url": ""},
    "additionalInfo": {
        "isAiGenerated": False, "isDraft": False,
        "collaborators": [], "mentions": [],
        "music": {"id": "", "artist": "", "name": "", "thumbnail": ""},
        "products": [], "tags": []
    },
    "replies": [],
    "accountId": ACCOUNT_ID,
    "scheduleAt": iso,
}

url = f"{BASE}/public/schedule"
body = json.dumps(payload).encode()
req = urllib.request.Request(url, data=body, headers=HEADERS, method="POST")

try:
    with urllib.request.urlopen(req) as resp:
        result = json.loads(resp.read())
    print(f"\n✅ SUCCESS!")
    print(f"  Schedule ID: {result.get('scheduleId', '?')}")
    print(f"  Scheduled at: {iso} ({iso[:19].replace('T', ' ')} WIB)")
except urllib.error.HTTPError as e:
    err_body = e.read().decode()
    print(f"\n❌ Error {e.code}: {err_body[:500]}")
    sys.exit(1)
except Exception as e:
    print(f"\n❌ Error: {e}")
    sys.exit(1)

