#!/usr/bin/env python3
"""
Generate Facebook ad image: Age Estimator UI concept for Good Bald
Simplified version using basic Gemini API call
"""

import os
import base64
import requests
from PIL import Image, ImageDraw, ImageFont
import io
import json

# Configure Gemini
API_KEY = "AIzaSyCXR9ftl7Rj3i8oNenEBfFQd5JnHdVSI2w"

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 and encode as base64
                img_byte_arr = io.BytesIO()
                img.save(img_byte_arr, format='PNG')
                img_bytes = img_byte_arr.getvalue()
                img_b64 = base64.b64encode(img_bytes).decode('utf-8')
                
                # Create content for API format
                image_part = {
                    "inline_data": {
                        "mime_type": "image/png",
                        "data": img_b64
                    }
                }
                image_parts.append(image_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 REST API"""
    
    # Create the prompt
    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."""

    # Prepare the request payload
    parts = []
    
    # Add product reference images
    for img_part in product_parts:
        parts.append(img_part)
    
    # Add the text prompt
    parts.append({"text": prompt})
    
    payload = {
        "contents": [{
            "parts": parts
        }]
    }
    
    print("Generating base image with Gemini...")
    
    try:
        # Make API request
        url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-flash-image-preview:generateContent?key={API_KEY}"
        
        headers = {
            "Content-Type": "application/json"
        }
        
        response = requests.post(url, json=payload, headers=headers)
        
        if response.status_code != 200:
            print(f"API Error: {response.status_code}")
            print(f"Response: {response.text}")
            return None
        
        result = response.json()
        
        # Extract the generated image
        if "candidates" in result and len(result["candidates"]) > 0:
            candidate = result["candidates"][0]
            if "content" in candidate and "parts" in candidate["content"]:
                for part in candidate["content"]["parts"]:
                    if "inline_data" in part and "data" in 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))
        
        print("No image data found in response")
        print(f"Response structure: {json.dumps(result, indent=2)}")
        return None
        
    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/Helvetica.ttc", 36)
        # Main text - medium
        main_font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 32)
        # Brand text - smaller
        brand_font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 24)
        # Confidence text - small
        small_font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 18)
    except:
        print("Using default fonts...")
        try:
            age_font = ImageFont.truetype("/System/Library/Fonts/Arial.ttf", 36)
            main_font = ImageFont.truetype("/System/Library/Fonts/Arial.ttf", 32)
            brand_font = ImageFont.truetype("/System/Library/Fonts/Arial.ttf", 24)
            small_font = ImageFont.truetype("/System/Library/Fonts/Arial.ttf", 18)
        except:
            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
    try:
        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))
    except:
        # Fallback if textbbox doesn't work
        draw.text((100, message_y), message, font=main_font, fill=(255, 255, 255))
        draw.text((150, message_y + 40), "We make sure you feel it too.", font=brand_font, fill=(200, 200, 200))
        draw.text((400, 1020), "goodbald.com", 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")
            return True
    else:
        print("✗ Error: Final image file not found")
        return False

if __name__ == "__main__":
    success = main()
    if success:
        print("\n🎉 Task completed successfully!")
    else:
        print("\n❌ Task failed!")