#!/usr/bin/env python3
"""
Generate thumbnail artikel untuk posting sosial media.
Gaya: BG biru StudioSoft (#1E40AF), font putih, judul artikel di tengah.
"""
from PIL import Image, ImageDraw, ImageFont
import os, textwrap

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

W, H = 1200, 630  # Standard OG image size
BLUE = (30, 64, 175)
WHITE = (255, 255, 255)
LIGHT_BLUE = (219, 234, 254)

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

def font(name, size):
    return ImageFont.truetype(os.path.join(FONT_DIR, name), size)

BOLD48 = font("Poppins-Bold.ttf", 48)
BOLD36 = font("Poppins-Bold.ttf", 36)
REG24 = font("Poppins-Regular.ttf", 24)
BOLD20 = font("Poppins-Bold.ttf", 20)

def wrap_text(text, font, max_width):
    words = text.split()
    lines = []
    current = ""
    for w in words:
        test = current + (" " if current else "") + w
        bbox = font.getbbox(test)
        if bbox[2] - bbox[0] <= max_width:
            current = test
        else:
            if current:
                lines.append(current)
            current = w
    if current:
        lines.append(current)
    return lines

def generate_thumbnail(artikel_id, title, topic):
    """Buat thumbnail artikel dengan judul di tengah"""
    img = Image.new("RGB", (W, H), BLUE)
    d = ImageDraw.Draw(img)
    
    # Header
    d.text((60, 40), "STUDIOSOFT", font=BOLD20, fill=LIGHT_BLUE)
    
    # Topic label
    d.text((60, 75), topic.upper(), font=BOLD20, fill=WHITE)
    
    # Garis dekoratif
    d.rectangle([60, 120, 300, 124], fill=LIGHT_BLUE)
    
    # Judul artikel — auto wrap
    max_w = W - 120
    lines = wrap_text(title, BOLD48, max_w)
    
    # Kalo judul terlalu panjang, turunin font size
    if len(lines) > 3:
        lines = wrap_text(title, BOLD36, max_w)
    
    total_h = len(lines) * 65
    start_y = (H - total_h) // 2 - 20
    
    for i, line in enumerate(lines):
        d.text((60, start_y + i * 65), line, font=BOLD48 if len(lines) <= 3 else BOLD36, fill=WHITE)
    
    # Garis bawah
    bottom_y = start_y + total_h + 30
    d.rectangle([60, bottom_y, min(400, W - 60), bottom_y + 4], fill=WHITE)
    
    # Footer
    d.text((60, H - 50), "studiosoft.id", font=REG24, fill=LIGHT_BLUE)
    d.text((W - 60, H - 50), "#Artikel", font=REG24, fill=LIGHT_BLUE, anchor="rt")
    
    fname = f"artikel_{artikel_id}.png"
    fpath = os.path.join(OUT_DIR, fname)
    img.save(fpath)
    return fpath

if __name__ == "__main__":
    # Test
    fpath = generate_thumbnail(999, "Test Judul Artikel", "Test Topic")
    print(f"✅ Test thumbnail: {fpath}")
