#!/usr/bin/env python3

import os
import google.generativeai as genai
from PIL import Image, ImageDraw, ImageFont
import io

# Configure Gemini
genai.configure(api_key="AIzaSyCXR9ftl7Rj3i8oNenEBfFQd5JnHdVSI2w")

def resize_image(image_path, target_size=512):
    """Resize image to target size while maintaining aspect ratio"""
    with Image.open(image_path) as img:
        img = img.convert('RGB')
        img.thumbnail((target_size, target_size), Image.Resampling.LANCZOS)
        return img

def load_product_images():
    """Load and resize all Good Bald product images"""
    product_dir = "/Users/igloo/.openclaw/workspace/goodbald-images/original"
    product_images = []
    
    image_files = [
        "after-shave-treatment-spray.png",
        "post-shave-moisturizer.png", 
        "pre-shave-scrub.png",
        "shave-cream-bentonite-clay.png",
        "shave-cream-tea-tree.png"
    ]
    
    for filename in image_files:
        image_path = os.path.join(product_dir, filename)
        if os.path.exists(image_path):
            resized_img = resize_image(image_path)
            # Convert PIL image to bytes for Gemini
            img_bytes = io.BytesIO()
            resized_img.save(img_bytes, format='PNG')
            img_bytes = img_bytes.getvalue()
            product_images.append(img_bytes)
            print(f"Loaded: {filename}")
    
    return product_images

def generate_meme_base():
    """Generate the base meme image using Gemini"""
    print("Loading product images...")
    product_images = load_product_images()
    
    # Initialize Gemini model
    model = genai.GenerativeModel('gemini-3.1-flash-image-preview')
    
    # Create parts list with product images
    parts = []
    for img_bytes in product_images:
        parts.append({
            "inline_data": {
                "mime_type": "image/png",
                "data": img_bytes
            }
        })
    
    # Add the text prompt
    prompt = """Create a two-panel meme image in the style of the Drake meme or Virgin vs Chad format. 1080x1080 square format.

TOP PANEL (rejection/cringe side):
- A guy desperately clinging to his remaining thin hair, doing a combover, looking insecure and stressed
- Should convey "holding onto something that's clearly not working"
- Red X or disapproval energy
- Slightly awkward, relatable but cringe energy

BOTTOM PANEL (approval/based side):
- A confident, clean-shaved bald man looking like an absolute boss
- Include some of the Good Bald products visible in the scene (the bottles/containers from the reference images)
- Should convey confidence, self-acceptance, and looking great
- Green check or approval energy
- The man should look moisturized, glowing, and confident

Style notes:
- Internet meme aesthetic - slightly rough around the edges, not corporate polished
- Relatable and shareable
- Clear visual distinction between the two panels
- Do NOT include any text overlays - just the visual scenes
- Make sure it's clearly a two-panel comparison format
- 1080x1080 square aspect ratio"""
    
    parts.append(prompt)
    
    print("Generating base meme image with Gemini...")
    response = model.generate_content(parts)
    
    if hasattr(response, 'parts') and response.parts:
        for part in response.parts:
            if hasattr(part, 'inline_data'):
                return part.inline_data.data
    
    raise Exception("No image generated by Gemini")

def add_text_overlays(image_data):
    """Add text overlays to the generated meme"""
    print("Adding text overlays...")
    
    # Load the generated image
    img = Image.open(io.BytesIO(image_data))
    draw = ImageDraw.Draw(img)
    
    # Try to load a font, fall back to default if needed
    try:
        # Try system fonts
        font_large = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 48)
        font_medium = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 36)
        font_small = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 28)
    except:
        try:
            # Try alternative font paths
            font_large = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 48)
            font_medium = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 36)
            font_small = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 28)
        except:
            # Fall back to default font
            font_large = ImageFont.load_default()
            font_medium = ImageFont.load_default() 
            font_small = ImageFont.load_default()
    
    # Image is 1080x1080, so top panel is roughly 0-540, bottom panel is 540-1080
    
    # Top panel text: "❌ Holding onto 12 remaining hairs"
    top_text = "❌ Holding onto 12 remaining hairs"
    
    # Calculate text position for top panel (centered horizontally, positioned in top third)
    bbox = draw.textbbox((0, 0), top_text, font=font_medium)
    text_width = bbox[2] - bbox[0]
    text_height = bbox[3] - bbox[1]
    
    top_x = (1080 - text_width) // 2
    top_y = 180  # Position in upper portion of top panel
    
    # Draw text with outline for better readability
    outline_color = "black"
    text_color = "white"
    
    # Draw outline
    for dx in [-2, -1, 0, 1, 2]:
        for dy in [-2, -1, 0, 1, 2]:
            if dx != 0 or dy != 0:
                draw.text((top_x + dx, top_y + dy), top_text, fill=outline_color, font=font_medium)
    
    # Draw main text
    draw.text((top_x, top_y), top_text, fill=text_color, font=font_medium)
    
    # Bottom panel text: "✅ Shaved, moisturized, glowing"
    bottom_text = "✅ Shaved, moisturized, glowing"
    
    bbox = draw.textbbox((0, 0), bottom_text, font=font_medium)
    text_width = bbox[2] - bbox[0]
    
    bottom_x = (1080 - text_width) // 2
    bottom_y = 720  # Position in upper portion of bottom panel
    
    # Draw outline
    for dx in [-2, -1, 0, 1, 2]:
        for dy in [-2, -1, 0, 1, 2]:
            if dx != 0 or dy != 0:
                draw.text((bottom_x + dx, bottom_y + dy), bottom_text, fill=outline_color, font=font_medium)
    
    # Draw main text
    draw.text((bottom_x, bottom_y), bottom_text, fill=text_color, font=font_medium)
    
    # Add website URL in bottom corner
    url_text = "goodbald.com"
    bbox = draw.textbbox((0, 0), url_text, font=font_small)
    text_width = bbox[2] - bbox[0]
    
    url_x = 1080 - text_width - 20  # 20px padding from right edge
    url_y = 1080 - 40  # 40px from bottom
    
    # Draw outline for URL
    for dx in [-1, 0, 1]:
        for dy in [-1, 0, 1]:
            if dx != 0 or dy != 0:
                draw.text((url_x + dx, url_y + dy), url_text, fill=outline_color, font=font_small)
    
    # Draw main URL text
    draw.text((url_x, url_y), url_text, fill="white", font=font_small)
    
    return img

def main():
    try:
        # Generate base image
        image_data = generate_meme_base()
        
        # Add text overlays
        final_image = add_text_overlays(image_data)
        
        # Ensure output directory exists
        output_dir = "/Users/igloo/.openclaw/workspace/scratch"
        os.makedirs(output_dir, exist_ok=True)
        
        # Save final image
        output_path = os.path.join(output_dir, "creative-meme-bald.png")
        final_image.save(output_path, "PNG")
        
        print(f"✅ Meme image saved successfully: {output_path}")
        print(f"📐 Image dimensions: {final_image.size}")
        
        # Verify success criteria
        width, height = final_image.size
        if width == 1080 and height == 1080:
            print("✅ Image is correct 1080x1080 format")
        else:
            print(f"⚠️  Image dimensions are {width}x{height}, expected 1080x1080")
            
    except Exception as e:
        print(f"❌ Error generating meme: {str(e)}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()