#!/usr/bin/env python3
"""
StudioSoft — GEO Carousel (3 Slides)
Layout persis studiosoft_bg_biru.py — konten GEO
Margin 50px rata • Konten vertical-middle
Judul 100px Poppins Bold • Body 28px Poppins Regular
1080x1350 (4:5) • BG Biru #1E40AF
"""

from PIL import Image, ImageDraw, ImageFont
import base64, json, os, urllib.request, urllib.error
from repliz_client import HEADERS, BASE_URL

OUT_DIR = "/home/mantapman/.hermes/profiles/atun/workspace/studiosoft_geo_final"
os.makedirs(OUT_DIR, exist_ok=True)

W, H = 1080, 1350
BG = (30, 64, 175)
WHITE = (255, 255, 255)
M = 50
CONTENT_W = W - 2*M  # 980

FD = os.path.expanduser("~/.fonts")

J100 = ImageFont.truetype(f"{FD}/Poppins-Bold.ttf", 100)
B36  = ImageFont.truetype(f"{FD}/Poppins-Bold.ttf", 36)
R28  = ImageFont.truetype(f"{FD}/Poppins-Regular.ttf", 28)
R22  = ImageFont.truetype(f"{FD}/Poppins-Regular.ttf", 22)
R20  = ImageFont.truetype(f"{FD}/Poppins-Regular.ttf", 20)

def fw(d, text, font):
    return d.textbbox((0,0), text, font=font)[2]

def fh(d, text, font):
    b = d.textbbox((0,0), text, font=font)
    return b[3] - b[1]

def wrap(d, text, font, mx):
    lines = []
    for p in text.split("\n"):
        ws = p.split()
        cur = ""
        for w in ws:
            t = (cur + " " + w) if cur else w
            if fw(d, t, font) > mx and cur:
                lines.append(cur)
                cur = w
            else:
                cur = t
        if cur: lines.append(cur)
    return lines

def block_h(d, content, font, mx, ls=1.35):
    lines = wrap(d, content, font, mx)
    total = 0
    for line in lines:
        lh = fh(d, line, font)
        total += int(lh * ls)
    return total

def draw_block(d, text, x, y, font, fill, mx, ls=1.35):
    for line in wrap(d, text, font, mx):
        lh = fh(d, line, font)
        d.text((x, y), line, font=font, fill=fill)
        y += int(lh * ls)
    return y

def header(d, page):
    d.text((M, M), "STUDIOSOFT", font=B36, fill=WHITE)
    d.text((W-M, M), page, font=R22, fill=WHITE, anchor="rt")

def divider(d, x, y, w=300):
    dx = x
    while dx < x + w:
        e = min(dx + 14, x + w)
        d.line([(dx, y), (e, y)], fill=WHITE, width=2)
        dx += 24

def footer(d, left="www.studiosoft.id", right=""):
    d.text((M, H-130), left, font=R20, fill=WHITE)
    if right:
        d.text((W-M, H-130), right, font=R20, fill=WHITE, anchor="rt")

def clean_edges(im):
    px = im.load()
    for y in range(H):
        for x in range(3): px[x,y] = BG
        for x in range(W-3, W): px[x,y] = BG
    for y in range(H-5, H):
        for x in range(W): px[x,y] = BG
    for x in range(W):
        for y in range(3): px[x,y] = BG

# ==========================================
# SLIDE 1 — COVER
# ==========================================
im = Image.new("RGB", (W, H), BG)
d = ImageDraw.Draw(im)
header(d, "01/03")

hdr_h = fh(d, "STUDIOSOFT", B36)
total_h = 0

# Title lines
for t in ["GEO", "GENERATIVE ENGINE", "OPTIMIZATION"]:
    total_h += int(fh(d, t, J100) * 1.15)

# Divider
divider_w = 300
total_h += 60 + 5 + 55

# Subtitle
sub_h = block_h(d, "Strategi Baru Biar Brandmu Disebut di Jawaban AI", R28, CONTENT_W)
total_h += sub_h + 20

# Check items
check_h = 0
for item in ["☑  Optimasi untuk ChatGPT, Gemini & AI Lainnya",
             "☑  Bukan SEO Biasa"]:
    check_h += int(fh(d, item, R28) * 1.3)
total_h += check_h

usable = H - 2*M - hdr_h - 20
start_y = M + hdr_h + 20 + (usable - total_h) // 2

ty = start_y
for t in ["GEO", "GENERATIVE ENGINE", "OPTIMIZATION"]:
    d.text((M, ty), t, font=J100, fill=WHITE)
    ty += int(fh(d, t, J100) * 1.15)

ty += 30
divider(d, M, ty, divider_w)
ty += 25

ty = draw_block(d, "Strategi Baru Biar Brandmu Disebut di Jawaban AI", M, ty, R28, WHITE, CONTENT_W)
ty += 15

for item in ["☑  Optimasi untuk ChatGPT, Gemini & AI Lainnya",
             "☑  Bukan SEO Biasa"]:
    d.text((M, ty), item, font=R28, fill=WHITE)
    ty += int(fh(d, item, R28) * 1.3)

footer(d, "studiosoft.id", "Swipe →")
clean_edges(im)
im.save(f"{OUT_DIR}/01_cover.jpg", quality=88)
print("✅ 01_cover.jpg")

# ==========================================
# SLIDE 2 — KENALAN
# ==========================================
im = Image.new("RGB", (W, H), BG)
d = ImageDraw.Draw(im)
header(d, "02/03")

total_h = 0
# Title
j_h = int(fh(d, "APA ITU", J100) * 1.15)
j2_h = int(fh(d, "GEO?", J100) * 1.15)
total_h += j_h + 15 + j2_h + 60 + 5 + 55

# Description
desc = "Generative Engine Optimization adalah strategi optimasi\nkonten biar brand dan websitemu muncul sebagai\nreferensi di jawaban AI."
desc_h = block_h(d, desc, R28, CONTENT_W)
total_h += desc_h + 15

# Check items
for item in ["☑  SEO ranking di 10 link biru Google",
             "☑  GEO AI memahami, milih & ngutip kontenmu",
             "☑  Keduanya saling melengkapi"]:
    total_h += int(fh(d, item, R28) * 1.3)

usable = H - 2*M - hdr_h - 20
start_y = M + hdr_h + 20 + (usable - total_h) // 2

ty = start_y
d.text((M, ty), "APA ITU", font=J100, fill=WHITE)
ty += j_h

d.text((M, ty), "GEO?", font=J100, fill=WHITE)
ty += j2_h

ty += 30
divider(d, M, ty, 300)
ty += 25

ty = draw_block(d, desc, M, ty, R28, WHITE, CONTENT_W)
ty += 10

for item in ["☑  SEO ranking di 10 link biru Google",
             "☑  GEO AI memahami, milih & ngutip kontenmu",
             "☑  Keduanya saling melengkapi"]:
    d.text((M, ty), item, font=R28, fill=WHITE)
    ty += int(fh(d, item, R28) * 1.3)

footer(d, "studiosoft.id")
clean_edges(im)
im.save(f"{OUT_DIR}/02_slide.jpg", quality=88)
print("✅ 02_slide.jpg")

# ==========================================
# SLIDE 3 — LAYANAN / CTA
# ==========================================
im = Image.new("RGB", (W, H), BG)
d = ImageDraw.Draw(im)
header(d, "03/03")

total_h = 0
titles_3 = ["KENAPA GEO", "PENTING?"]
for t in titles_3:
    total_h += int(fh(d, t, J100) * 1.15)
total_h += 60 + 5 + 55

for item in ["☑  73% search intent masih di Google (SparkToro)",
             "☑  800% kenaikan referral AI/LLM (Backlinko)",
             "☑  6,5x AI lebih sering ngutip brand pihak ke-3"]:
    total_h += int(fh(d, item, R28) * 1.3)

total_h += 20
last_h = block_h(d, "Yang adaptasi sekarang, yang menang di 2027.", R28, CONTENT_W)
total_h += last_h + 15
cta_h = block_h(d, "Konsultasi: 0819-3500-0624", R28, CONTENT_W)
total_h += cta_h

usable = H - 2*M - hdr_h - 20
start_y = M + hdr_h + 20 + (usable - total_h) // 2

ty = start_y
for t in titles_3:
    d.text((M, ty), t, font=J100, fill=WHITE)
    ty += int(fh(d, t, J100) * 1.15)

ty += 30
divider(d, M, ty, 300)
ty += 25

for item in ["☑  73% search intent masih di Google (SparkToro)",
             "☑  800% kenaikan referral AI/LLM (Backlinko)",
             "☑  6,5x AI lebih sering ngutip brand pihak ke-3"]:
    d.text((M, ty), item, font=R28, fill=WHITE)
    ty += int(fh(d, item, R28) * 1.3)

ty += 15
ty = draw_block(d, "Yang adaptasi sekarang, yang menang di 2027.", M, ty, R28, WHITE, CONTENT_W)
ty += 10
ty = draw_block(d, "Konsultasi: 0819-3500-0624", M, ty, R28, WHITE, CONTENT_W)

footer(d, "studiosoft.id")
clean_edges(im)
im.save(f"{OUT_DIR}/03_slide.jpg", quality=88)
print("✅ 03_slide.jpg")

print("\n✅ Selesai! 3 slides GEO.")

# ════════════ SCHEDULE ════════════
SLOT = "2026-07-25T13:00:00.000Z"
FILES = sorted([f for f in os.listdir(OUT_DIR) if f.endswith('.jpg')])
ACCOUNT = "6a335b9ec5ff4ce3a3225c2a"

def api_call(method, endpoint, data=None):
    url = f"{BASE_URL}{endpoint}"
    body = json.dumps(data).encode() if data else None
    req = urllib.request.Request(url, data=body, headers=HEADERS, method=method)
    try:
        with urllib.request.urlopen(req, timeout=15) as resp:
            raw = resp.read()
            return json.loads(raw) if raw else {"success": True}
    except Exception as e:
        return {"error": str(e)}

medias = []
for fname in sorted(FILES):
    with open(os.path.join(OUT_DIR, fname), "rb") as f:
        b64 = base64.b64encode(f.read()).decode()
    medias.append({"url": f"data:image/jpeg;base64,{b64}", "type": "image", "alt": "GEO StudioSoft"})

caption = (
    "GEO (Generative Engine Optimization) adalah strategi baru "
    "yang nggak bisa diabaikan di 2026.\n\n"
    "SEO bikin brandmu ranking di Google. GEO bikin "
    "brandmu disebut di jawaban AI.\n\n"
    "Yang nggak siap sekarang, bakal ketinggalan.\n\n"
    "Slide by StudioSoft\nstudiosoft.id"
)

replies = [
    "SEO vs GEO:\n"
    "SEO = ranking keyword + backlink\n"
    "GEO = konten informatif + disebut AI\n\n"
    "Keduanya penting. Tapi ke depannya, "
    "AI makin jadi gerbang pertama konsumen.",

    "Data penting:\n"
    "73% search intent masih di Google\n"
    "800% kenaikan referral AI\n"
    "6,5x AI lebih suka brand dari pihak ke-3\n\n"
    "Yang adaptasi sekarang, yang menang di 2027.\nstudiosoft.id",
]

payload = {
    "title": "", "description": caption,
    "topic": "GEO, Generative Engine Optimization",
    "type": "album", "medias": medias,
    "meta": {"title": "", "description": "", "url": ""},
    "additionalInfo": {"isAiGenerated": False, "isDraft": False,
        "collaborators": [], "mentions": [],
        "music": {"id":"","artist":"","name":"","thumbnail":""},
        "products": [], "tags": []},
    "replies": [{"text": r, "username": ""} for r in replies],
    "accountId": ACCOUNT, "scheduleAt": SLOT,
}

print("\n" + "=" * 50)
print("SCHEDULING: StudioSoft Threads")
print(f"Slot: {SLOT} (20:00 WIB)")
print("=" * 50)

r = api_call("POST", "/public/schedule", payload)
if "error" in r:
    print(f"ERROR: {r['error']}")
else:
    print(f"SUCCESS! ID: {r.get('scheduleId','?')}")
print("\nDONE")
