#!/usr/bin/env python3
"""
Generate Facebook ad image: Age Estimator UI concept for Good Bald
Uses Gemini image generation with Good Bald product references
"""

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

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

def load_and_resize_product_images():
    """Load and resize all Good Bald product images to ~512px as reference"""
    product_dir = "/Users/igloo/.openclaw/workspace/goodbald-images/original"
    product_files = [
        "after-shave-treatment-spray.png",
        "post-shave-moisturizer.png", 
        "pre-shave-scrub.png",
        "shave-cream-bentonite-clay.png",
        "shave-cream-tea-tree.png"
    ]
    
    image_parts = []
    
    for filename in product_files:
        filepath = os.path.join(product_dir, filename)
        if os.path.exists(filepath):
            print(f"Loading {filename}...")
            
            # Load and resize image
            with Image.open(filepath) as img:
                # Convert to RGB if needed
                if img.mode != 'RGB':
                    img = img.convert('RGB')
                
                # Resize to ~512px max dimension
                img.thumbnail((512, 512), Image.Resampling.LANCZOS)
                
                # Convert to bytes
                img_byte_arr = io.BytesIO()
                img.save(img_byte_arr, format='PNG')
                img_bytes = img_byte_arr.getvalue()
                
                # Create Part for Gemini
                part = types.Part.from_bytes(data=img_bytes, mime_type="image/png")
                image_parts.append(part)
        else:
            print(f"Warning: {filename} not found")
    
    return image_parts

def generate_base_image_with_gemini(product_parts):
    """Generate the base age estimator UI image using Gemini"""
    
    # Initialize the model
    model = genai.GenerativeModel('gemini-3.1-flash-image-preview')
    
    # Create the prompt (no text overlays - we'll add those with PIL)
    prompt = """Generate a realistic mobile app or website screenshot showing an "AI Age Estimator" interface. Create a vertical layout with two main sections:

TOP SECTION: Show a man with visible balding/receding hairline, male pattern baldness. He should look around 40-45 years old. Surround his face with futuristic UI elements like:
- Facial recognition scan lines and detection boxes
- Digital overlay elements that look like AI analysis is happening
- Tech-style interface elements

BOTTOM SECTION: Show the same type of man but with a perfectly shaved bald head, clear glowing healthy skin. He should look noticeably younger and more confident. Same style of AI analysis UI elements around his face.

Make the overall design look like a sophisticated tech app with a modern dark interface. Include subtle gradient backgrounds, glowing elements, and high-tech visual effects. The men should be photorealistic and the UI should look believable as an actual age detection app.

Style: Modern tech app, dark theme with blue/cyan accents, professional photography, realistic facial features, sophisticated UI design.

DO NOT include any text, numbers, or brand names in the generated image - just the visual elements and interface design."""

    # Combine product images with the text prompt  
    content = product_parts + [prompt]
    
    print("Generating base image with Gemini...")
    try:
        response = model.generate_content(content)
        
        # Get the generated image
        if response.candidates and len(response.candidates) > 0:
            candidate = response.candidates[0]
            if candidate.content and candidate.content.parts:
                for part in candidate.content.parts:
                    if hasattr(part, 'inline_data') and part.inline_data:
                        image_data = part.inline_data.data
                        # Decode base64 image data
                        image_bytes = base64.b64decode(image_data)
                        return Image.open(io.BytesIO(image_bytes))
        
        raise Exception("No image data found in response")
        
    except Exception as e:
        print(f"Error generating image: {e}")
        return None

def add_text_overlays(base_image):
    """Add text overlays, age numbers, and branding using PIL"""
    
    # Resize base image to 1080x1080
    final_image = base_image.resize((1080, 1080), Image.Resampling.LANCZOS)
    draw = ImageDraw.Draw(final_image)
    
    # Try to load system fonts (fallback to default if not found)
    try:
        # Age numbers - large and bold
        age_font = ImageFont.truetype("/System/Library/Fonts/Arial.ttf", 36)
        # Main text - medium
        main_font = ImageFont.truetype("/System/Library/Fonts/Arial.ttf", 32)
        # Brand text - smaller
        brand_font = ImageFont.truetype("/System/Library/Fonts/Arial.ttf", 24)
        # Confidence text - small
        small_font = ImageFont.truetype("/System/Library/Fonts/Arial.ttf", 18)
    except:
        print("Using default fonts...")
        age_font = ImageFont.load_default()
        main_font = ImageFont.load_default() 
        brand_font = ImageFont.load_default()
        small_font = ImageFont.load_default()
    
    # Add age estimation boxes and text
    # Top section - "Estimated Age: 42"
    top_y = 200  # Adjust based on where the top face appears
    draw.rounded_rectangle([40, top_y, 300, top_y + 60], radius=8, fill=(0, 0, 0, 180))
    draw.text((50, top_y + 10), "Estimated Age:", font=small_font, fill=(255, 255, 255))
    draw.text((50, top_y + 30), "42", font=age_font, fill=(255, 100, 100))
    
    # Add confidence percentage
    draw.text((200, top_y + 35), "94% confidence", font=small_font, fill=(150, 150, 150))
    
    # Bottom section - "Estimated Age: 35" 
    bottom_y = 600  # Adjust based on where the bottom face appears
    draw.rounded_rectangle([40, bottom_y, 300, bottom_y + 60], radius=8, fill=(0, 0, 0, 180))
    draw.text((50, bottom_y + 10), "Estimated Age:", font=small_font, fill=(255, 255, 255))
    draw.text((50, bottom_y + 30), "35", font=age_font, fill=(100, 255, 100))
    
    # Add confidence percentage
    draw.text((200, bottom_y + 35), "96% confidence", font=small_font, fill=(150, 150, 150))
    
    # Add main message at bottom
    message = "The internet thinks you look 7 years younger bald."
    message_y = 950
    
    # Add semi-transparent background for text
    message_bbox = draw.textbbox((0, 0), message, font=main_font)
    message_width = message_bbox[2] - message_bbox[0]
    message_x = (1080 - message_width) // 2
    
    draw.rounded_rectangle([message_x - 20, message_y - 15, message_x + message_width + 20, message_y + 50], 
                          radius=10, fill=(0, 0, 0, 200))
    draw.text((message_x, message_y), message, font=main_font, fill=(255, 255, 255))
    
    # Add tagline
    tagline = "We make sure you feel it too."
    tagline_y = message_y + 40
    tagline_bbox = draw.textbbox((0, 0), tagline, font=brand_font)
    tagline_width = tagline_bbox[2] - tagline_bbox[0] 
    tagline_x = (1080 - tagline_width) // 2
    
    draw.text((tagline_x, tagline_y), tagline, font=brand_font, fill=(200, 200, 200))
    
    # Add brand
    brand_text = "goodbald.com"
    brand_y = 1020
    brand_bbox = draw.textbbox((0, 0), brand_text, font=brand_font)
    brand_width = brand_bbox[2] - brand_bbox[0]
    brand_x = (1080 - brand_width) // 2
    
    draw.text((brand_x, brand_y), brand_text, font=brand_font, fill=(100, 150, 255))
    
    return final_image

def main():
    """Main function to generate the complete Facebook ad"""
    
    print("=== Good Bald Age Estimator Facebook Ad Generator ===")
    
    # Step 1: Load product reference images
    print("\n1. Loading Good Bald product images as reference...")
    product_parts = load_and_resize_product_images()
    print(f"Loaded {len(product_parts)} product reference images")
    
    if len(product_parts) == 0:
        print("Error: No product images loaded. Cannot proceed.")
        return
    
    # Step 2: Generate base image with Gemini
    print("\n2. Generating base image with Gemini...")
    base_image = generate_base_image_with_gemini(product_parts)
    
    if base_image is None:
        print("Error: Failed to generate base image")
        return
    
    print(f"✓ Base image generated: {base_image.size}")
    
    # Step 3: Add text overlays with PIL
    print("\n3. Adding text overlays and branding...")
    final_image = add_text_overlays(base_image)
    
    # Step 4: Save final image
    output_path = "/Users/igloo/.openclaw/workspace/scratch/creative-age-estimator.png"
    print(f"\n4. Saving final image to {output_path}")
    
    final_image.save(output_path, "PNG", quality=95)
    
    # Verify the output
    if os.path.exists(output_path):
        with Image.open(output_path) as img:
            print(f"✓ Success! Final image saved: {img.size}")
            print(f"✓ File size: {os.path.getsize(output_path) / 1024:.1f} KB")
    else:
        print("✗ Error: Final image file not found")

if __name__ == "__main__":
    main()