#!/usr/bin/env python3
"""
CE LinkedIn Post Image Generator
Style: Black bg, white serif, red accent words
Format: 1200x628 (LinkedIn standard)
"""

import sys
from PIL import Image, ImageDraw, ImageFont
import re
import textwrap

def generate_ce_image(text_parts, output_path, width=1200, height=628):
    """
    text_parts: list of (word/phrase, color) tuples
    Colors: 'white' or 'red'
    """
    # Create black canvas
    img = Image.new('RGB', (width, height), color=(0, 0, 0))
    draw = ImageDraw.Draw(img)

    # Colors
    WHITE = (255, 255, 255)
    RED = (200, 30, 30)  # CE red — matches the header image

    # Try to load Playfair Display, fallback to Liberation Serif
    font_path = '/tmp/PlayfairDisplay.ttf'
    fallback = '/usr/share/fonts/truetype/liberation/LiberationSerif-Regular.ttf'

    font_size = 58
    try:
        font = ImageFont.truetype(font_path, font_size)
    except:
        font = ImageFont.truetype(fallback, font_size)

    # Build segments: list of (text, color)
    # text_parts already provided as segments
    
    # Measure total width of the line
    total_width = 0
    char_data = []
    for (segment, color) in text_parts:
        bbox = draw.textbbox((0, 0), segment, font=font)
        w = bbox[2] - bbox[0]
        h = bbox[3] - bbox[1]
        char_data.append((segment, color, w, h))
        total_width += w

    # Handle multi-line: if total width > 90% of canvas, we need to wrap
    max_line_width = int(width * 0.82)
    
    if total_width <= max_line_width:
        # Single line — center vertically and horizontally
        lines = [text_parts]
    else:
        # Need to do word-level line breaking
        # Reconstruct full text and wrap, then re-apply colors
        full_text = ''.join(seg for seg, _ in text_parts)
        words = full_text.split()
        
        # Build word->color map
        word_colors = {}
        for (segment, color) in text_parts:
            seg_words = segment.strip().split()
            for w in seg_words:
                word_colors[w.lower().strip('.,!?')] = color
        
        # Wrap into lines
        lines_text = []
        current_line = []
        current_w = 0
        for word in words:
            word_with_space = word + ' '
            bbox = draw.textbbox((0, 0), word_with_space, font=font)
            word_w = bbox[2] - bbox[0]
            if current_w + word_w > max_line_width and current_line:
                lines_text.append(' '.join(current_line))
                current_line = [word]
                current_w = word_w
            else:
                current_line.append(word)
                current_w += word_w
        if current_line:
            lines_text.append(' '.join(current_line))
        
        # Re-map colors to line segments
        lines = []
        for line_str in lines_text:
            line_segs = []
            line_words = line_str.split()
            i = 0
            while i < len(line_words):
                word = line_words[i]
                clean = word.lower().strip('.,!?')
                color = word_colors.get(clean, 'white')
                # Merge consecutive same-color words
                merged = word
                while i + 1 < len(line_words):
                    next_word = line_words[i + 1]
                    next_clean = next_word.lower().strip('.,!?')
                    next_color = word_colors.get(next_clean, 'white')
                    if next_color == color:
                        merged += ' ' + next_word
                        i += 1
                    else:
                        break
                line_segs.append((merged, color))
                i += 1
            lines.append(line_segs)

    # Calculate total text block height
    line_height = font_size + 20
    total_text_height = len(lines) * line_height
    
    # Starting Y — center the text block, nudged slightly up for elegance
    start_y = (height - total_text_height) // 2 - 10

    def seg_width(seg):
        # Use a space-padded reference to measure correctly
        # Measure "X" + seg + "X", then subtract 2*X widths
        ref = draw.textbbox((0, 0), "X" + seg + "X", font=font)
        x_ref = draw.textbbox((0, 0), "XX", font=font)
        return (ref[2] - ref[0]) - (x_ref[2] - x_ref[0])

    for line_idx, line_segs in enumerate(lines):
        # Calculate total line width accurately
        line_w = sum(seg_width(seg) for seg, _ in line_segs)
        
        # Start X for centering
        x = (width - line_w) // 2
        y = start_y + line_idx * line_height

        for (segment, color_name) in line_segs:
            color = RED if color_name == 'red' else WHITE
            draw.text((x, y), segment, font=font, fill=color)
            x += seg_width(segment)

    # CE brand watermark — bottom right
    small_font_size = 20
    try:
        small_font = ImageFont.truetype(font_path, small_font_size)
    except:
        small_font = ImageFont.truetype(fallback, small_font_size)
    
    brand_text = "curiousendeavor.com"
    brand_color = (100, 100, 100)
    bb = draw.textbbox((0, 0), brand_text, font=small_font)
    brand_w = bb[2] - bb[0]
    draw.text((width - brand_w - 40, height - 45), brand_text, font=small_font, fill=brand_color)

    img.save(output_path, 'PNG', quality=95)
    print(f'MEDIA: {output_path}')
    return output_path


if __name__ == '__main__':
    # Post #1 — Tool Stack vs System
    # Using explicit multi-line: pass each line as a separate segment group
    # Format: list of lines, each line is list of (text, color)
    # We'll use a simpler direct approach for precise control
    
    img = Image.new('RGB', (1200, 628), color=(0, 0, 0))
    draw = ImageDraw.Draw(img)
    
    WHITE = (255, 255, 255)
    RED = (200, 30, 30)
    GRAY = (100, 100, 100)
    
    font_path = '/tmp/PlayfairDisplay.ttf'
    fallback = '/usr/share/fonts/truetype/liberation/LiberationSerif-Regular.ttf'
    
    try:
        font_lg = ImageFont.truetype(font_path, 60)
        font_sm = ImageFont.truetype(font_path, 20)
    except:
        font_lg = ImageFont.truetype(fallback, 60)
        font_sm = ImageFont.truetype(fallback, 20)
    
    width, height = 1200, 628
    
    def draw_line(draw, segments, font, y, canvas_width):
        """Draw a line of colored text segments, centered."""
        def sw(text):
            bb = draw.textbbox((0,0), text, font=font)
            return bb[2] - bb[0]
        
        total_w = sum(sw(seg) for seg, _ in segments)
        x = (canvas_width - total_w) // 2
        
        for (seg, color) in segments:
            draw.text((x, y), seg, font=font, fill=color)
            x += sw(seg)
    
    line_height = 90   # generous spacing between lines
    num_lines = 2
    block_h = num_lines * 60 + (num_lines - 1) * (line_height - 60)
    start_y = (height - block_h) // 2 - 10  # slight optical upward nudge

    # Line 1
    draw_line(draw, [
        ("Most brands are building a ", WHITE),
        ("tool stack.", RED),
    ], font_lg, y=start_y, canvas_width=width)
    
    # Line 2
    draw_line(draw, [
        ("Not a ", WHITE),
        ("system.", RED),
    ], font_lg, y=start_y + line_height, canvas_width=width)
    
    # CE watermark — centered at bottom
    brand_text = "curiousendeavor.com"
    bb = draw.textbbox((0,0), brand_text, font=font_sm)
    brand_w = bb[2] - bb[0]
    draw.text(((width - brand_w) // 2, height - 48), brand_text, font=font_sm, fill=GRAY)
    
    out = '/root/.openclaw/workspace/2026-03-19-lukas-linkedin-post1.png'
    img.save(out, 'PNG')
    print(f'MEDIA: {out}')
