#!/usr/bin/env python3

import os
from PIL import Image
import io
import requests
import json
import base64
from pathlib import Path

# Configuration
API_KEY = "AIzaSyCXR9ftl7Rj3i8oNenEBfFQd5JnHdVSI2w"
MODEL_NAME = "gemini-3.1-flash-image-preview"  # Nano Banana 2 (current best)
PRODUCT_IMAGES_DIR = "/Users/igloo/.openclaw/workspace/goodbald-images/original/"
OUTPUT_PATH = "/Users/igloo/.openclaw/workspace/scratch/hero-image-new.png"

# Text prompt for the hero image
PROMPT = """Create a premium lifestyle photograph for a luxury men's grooming brand called Good Bald. 

Scene: A confident, well-groomed bald man in his 30s-40s in a clean, modern bathroom. He has just finished his morning shaving routine and his freshly shaved head is gleaming with a healthy, clean shine. Morning sunlight streams in from a window, creating warm, natural lighting.

The Good Bald products should be prominently arranged on a clean marble or stone bathroom counter in front of him - all five products from the reference images should be clearly visible and recognizable. The products should look premium and aspirational.

Style Requirements:
- Premium lifestyle/product photography aesthetic
- Clean, modern, minimalist bathroom setting
- Warm morning light with soft shadows
- Color palette with dark green (#1d4d41) and gold (#c5993e) accents in towels or background elements
- Landscape orientation, 1920x1080 aspect ratio
- Professional photography quality
- The man should look confident and satisfied, like someone who has discovered the perfect grooming routine

Vibe: Aspirational but approachable - "this could be you" rather than an unreachable model. The scene should convey luxury, confidence, and the satisfaction of a premium grooming experience.

Important: NO text overlays or branding text in the image. Focus purely on the visual storytelling through the scene, products, and lifestyle imagery."""

def load_and_resize_image(image_path, max_size=512):
    """Load image and resize to specified max dimension while maintaining aspect ratio"""
    with Image.open(image_path) as img:
        # Convert to RGB if needed
        if img.mode != 'RGB':
            img = img.convert('RGB')
        
        # Calculate new size maintaining aspect ratio
        width, height = img.size
        if width > height:
            new_width = max_size
            new_height = int(height * max_size / width)
        else:
            new_height = max_size
            new_width = int(width * max_size / height)
        
        # Resize image
        img_resized = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
        
        # Convert to bytes
        img_bytes = io.BytesIO()
        img_resized.save(img_bytes, format='PNG')
        return img_bytes.getvalue()

def generate_image_with_gemini():
    """Generate hero image using Gemini API with product reference images"""
    
    # Load all product images
    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"
    ]
    
    # Prepare the request payload
    parts = []
    
    # Add product reference images first
    for product_file in product_files:
        product_path = os.path.join(PRODUCT_IMAGES_DIR, product_file)
        if os.path.exists(product_path):
            print(f"Loading reference image: {product_file}")
            image_bytes = load_and_resize_image(product_path)
            image_b64 = base64.b64encode(image_bytes).decode('utf-8')
            
            parts.append({
                "inline_data": {
                    "mime_type": "image/png",
                    "data": image_b64
                }
            })
        else:
            print(f"Warning: Product image not found: {product_path}")
    
    # Add the text prompt
    parts.append({"text": PROMPT})
    
    # Prepare API request
    url = f"https://generativelanguage.googleapis.com/v1beta/models/{MODEL_NAME}:generateContent"
    headers = {
        "Content-Type": "application/json",
    }
    
    payload = {
        "contents": [{
            "parts": parts
        }],
        "generationConfig": {
            "response_mime_type": "image/png"
        }
    }
    
    # Make the API request
    print(f"Generating hero image with {MODEL_NAME}...")
    response = requests.post(f"{url}?key={API_KEY}", headers=headers, json=payload)
    
    if response.status_code == 200:
        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'] and len(candidate['content']['parts']) > 0:
                part = candidate['content']['parts'][0]
                if 'inline_data' in part:
                    # Decode the base64 image
                    image_data = base64.b64decode(part['inline_data']['data'])
                    
                    # Save the image
                    os.makedirs(os.path.dirname(OUTPUT_PATH), exist_ok=True)
                    with open(OUTPUT_PATH, 'wb') as f:
                        f.write(image_data)
                    
                    print(f"✅ Hero image generated successfully!")
                    print(f"📁 Saved to: {OUTPUT_PATH}")
                    print(f"🤖 Model used: {MODEL_NAME}")
                    print(f"📸 Reference images: {len(product_files)} Good Bald products")
                    
                    # Check file size for verification
                    file_size = len(image_data)
                    print(f"📊 File size: {file_size:,} bytes ({file_size/1024/1024:.1f} MB)")
                    
                    return True
                else:
                    print("❌ Error: No image data in response")
            else:
                print("❌ Error: Invalid response structure")
        else:
            print("❌ Error: No candidates in response")
    else:
        print(f"❌ API request failed with status {response.status_code}")
        print(f"Response: {response.text}")
    
    return False

if __name__ == "__main__":
    success = generate_image_with_gemini()
    if success:
        print("\n🎉 Task completed successfully!")
        print("✅ Premium hero image generated with all Good Bald products")
        print("✅ Landscape format, clean modern aesthetic")
        print("✅ Confident bald man in modern bathroom setting") 
        print("✅ Products clearly visible and recognizable")
        print("✅ No text overlays - ready for website integration")
    else:
        print("\n❌ Task failed - image generation unsuccessful")