from repliz_client import upload_image_to_server
#!/usr/bin/env python3
"""StudioSoft IG Story — Sesi 1, 31 Juli 2026 (08:00 WIB)
Overlay: PUTIH 80% (selang-seling dari sesi terakhir Hitam 70%)
Topik: random dari pool, hindari yang baru dipakai (Social Media, Branding)
"""
from PIL import Image, ImageDraw, ImageFont
import base64, json, os, random, urllib.request, io, textwrap

# ===== CREDENTIALS =====
REPLIZ_AUTH = "NDY1NDYwOTg2NjpRQl..."  # placeholder, diisi di bawah
WP_AUTH = "Basic " + 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

# Repliz Basic Auth sesuai instruksi cron
REPLIZ_AUTH = "Basic " + "NDY1NDYwOTg2NjpRQlpaZ0hGeUxRTWlQYXRzVnFZ..."  # fixed di bawah

# ===== TOPIK POOL =====
TOPICS = [
    {
        "name": "SEO",
        "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!"
    },
    {
        "name": "Social Media",
        "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!"
    },
    {
        "name": "Digital Marketing",
        "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!"
    },
    {
        "name": "AI",
        "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!"
    },
    {
        "name": "Content Marketing",
        "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!"
    },
    {
        "name": "Branding",
        "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!"
    },
]

# Topik yang baru dipakai (hindari duplikasi)
RECENT = ["Social Media", "Branding"]
# Pilih random dari yang belum dipakai baru-baru ini
pool = [t for t in TOPICS if t["name"] not in RECENT]
random.seed()
topic = random.choice(pool)
chosen_topic_name = topic["name"]
print(f"🎯 Topik terpilih: {chosen_topic_name}")

# ===== DOWNLOAD BACKGROUND DARI PEXELS =====
PEXELS_KEY = "563492ad6f917567a4f9a6f6c8b1c8e1a0b5f5e5a6d7c8b9c0d1e2f3a4b5c6d7"
pexels_keywords = {
    "SEO": ["seo strategy laptop", "website analytics", "digital marketing laptop"],
    "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])

def download_pexels_bg(keyword):
    """Download bg dari Pexels, portrait, return PIL image"""
    try:
        url = ("https://api.pexels.com/v1/search?query=" + urllib.parse.quote(keyword) +
               "&per_page=10&orientation=portrait")
        req = urllib.request.Request(url, headers={"Authorization": PEXELS_KEY})
        with urllib.request.urlopen(req, timeout=20) as r:
            data = json.loads(r.read())
        photos = data.get("photos", [])
        if not photos:
            return None
        # pilih random photo
        photo = random.choice(photos)
        # ambil ukuran besar (landscape/portrait besar)
        img_url = photo.get("src", {}).get("large2x") or photo.get("src", {}).get("large")
        if not img_url:
            return None
        print(f"  📥 Download Pexels: {img_url}")
        urllib.request.urlretrieve(img_url, "/tmp/pexels_bg.jpg")
        img = Image.open("/tmp/pexels_bg.jpg").convert("RGB")
        return img
    except Exception as e:
        print(f"  Pexels gagal: {e}")
        return None

bg = download_pexels_bg(kw)

# Fallback gradient kalau Pexels gagal
if bg is None:
    print("  Pexels gagal — fallback gradient")
    bg = Image.new("RGB", (W, H), (240, 240, 245))
    grad = ImageDraw.Draw(bg)
    for y in range(H):
        progress = y / H
        r = int(240 + (218 - 240) * progress)
        g = int(240 + (226 - 240) * progress)
        b = int(248 + (236 - 248) * progress)
        grad.line([(0, y), (W, y)], fill=(r, g, b))
else:
    # Crop center ke 1080x1920
    w, h = bg.size
    target_ratio = W / H
    img_ratio = w / h
    if img_ratio > target_ratio:
        new_w = int(h * target_ratio)
        left = (w - new_w) // 2
        bg = bg.crop((left, 0, left + new_w, h))
    else:
        new_h = int(w / target_ratio)
        top = (h - new_h) // 2
        bg = bg.crop((0, top, w, top + new_h))
    bg = bg.resize((W, H), Image.LANCZOS)

# ===== 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)
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)
text_color = (30, 30, 30)  # gelap di atas putih

title_lines = topic["title"].split("\n")
body_lines = topic["body"].split("\n")

# Title start ~30% dari atas
cy = int(H * 0.20)
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

cy += 50
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 =====
# Ambil logo dari WP StudioSoft
logo_url = None
WP_AUTH_HEADER = "Basic " + base64.b64encode(b"bambangbot:qWYh MWiu BJL0 O6UI vxbt 11Ds").decode()
logged_in = False
try:
    wp_media_req = urllib.request.Request(
        "http://103.175.217.138/wp-json/wp/v2/media?search=logo&per_page=5",
        headers={
            "Authorization": WP_AUTH_HEADER,
            "Host": "studiosoft.id",
        }
    )
    with urllib.request.urlopen(wp_media_req, timeout=10) as r:
        media_list = json.loads(r.read())
    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:
        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 dari WP gagal: {e}")

# Footer text
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
else:
    # text logo fallback
    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_sesi1_31juli.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 (FIX 21/08)...")
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 =====
# Repliz Basic Auth dari instruksi cron
REPLIZ_AUTH = "Basic NDY1NDYwOTg2NjpRQlpaZ0hGeUxRTWlQYXRzVnFZc2FBbUJ0aE5ZUXh6Q0dZc2RrbkdHN0hSNzMxUlBYQ0p5VU5VYWVQZ0VwcGZGckFqaGxla2hSbzEyYw=="

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_payload = {
    "accountId": "6a38ac33c5ff4ce3a3231232",  # StudioSoft IG
    "scheduleAt": schedule_str,
    "type": "story",
    "medias": [{"url": source_url, "type": "image"}]
}
ig_headers = {"Authorization": REPLIZ_AUTH, "Content-Type": "application/json"}

print(f"📱 Schedule IG Story...")
try:
    ig_req = urllib.request.Request(REPLIZ_URL, data=json.dumps(ig_payload).encode(), headers=ig_headers, method="POST")
    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

# ===== RINGKASAN =====
print(f"\n{'='*60}")
print(f"📊 RINGKASAN STUDIOSOFT IG STORY — SESI 1")
print(f"{'='*60}")
print(f"  Tanggal : 31 Juli 2026")
print(f"  Sesi    : 1 (08: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"  Image   : {source_url}")
print(f"{'='*60}")

# Simpan state
state = {
    "date": "2026-07-31",
    "sesi": 1,
    "warna": "PUTIH",
    "opacity": "80%",
    "topik": chosen_topic_name,
    "ig_schedule_id": ig_schedule_id,
    "image_url": source_url,
    "schedule_at": schedule_str,
}
with open("memory/studiosoft_ig_story_state.json", "w") as f:
    json.dump(state, f, indent=2)
print(f"\n💾 State tersimpan di memory/studiosoft_ig_story_state.json")
