#!/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"
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_with_imagen():
    """Try Imagen 4.0 Ultra for image generation"""
    model_name = "imagen-4.0-ultra-generate-001"
    
    # 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
                }
            })
    
    # Add the text prompt
    parts.append({"text": PROMPT})
    
    # Prepare API request for Imagen
    url = f"https://generativelanguage.googleapis.com/v1beta/models/{model_name}:generateContent"
    headers = {
        "Content-Type": "application/json",
    }
    
    payload = {
        "contents": [{
            "parts": parts
        }]
    }
    
    print(f"Trying Imagen 4.0 Ultra: {model_name}...")
    response = requests.post(f"{url}?key={API_KEY}", headers=headers, json=payload)
    
    if response.status_code == 200:
        result = response.json()
        print("✅ Imagen API call successful!")
        
        # Try to extract image if present
        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:
                        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}")
                        return True
        
        # If no image data found, return the text response
        print("📝 Response received (text format):")
        print(json.dumps(result, indent=2))
        return False
    else:
        print(f"❌ Imagen API failed with status {response.status_code}")
        print(f"Response: {response.text}")
        return False

def list_available_models():
    """List available models to see what's actually available"""
    url = f"https://generativelanguage.googleapis.com/v1beta/models"
    response = requests.get(f"{url}?key={API_KEY}")
    
    if response.status_code == 200:
        models = response.json()
        print("Available models:")
        for model in models.get('models', []):
            name = model.get('name', '').replace('models/', '')
            print(f"  - {name}")
        return models
    else:
        print(f"Failed to list models: {response.status_code}")
        return None

def generate_with_basic_gemini():
    """Use basic Gemini for image analysis and description"""
    model_name = "gemini-3.1-flash-image-preview"
    
    # Load first product image as example
    product_path = os.path.join(PRODUCT_IMAGES_DIR, "shave-cream-bentonite-clay.png")
    image_bytes = load_and_resize_image(product_path)
    image_b64 = base64.b64encode(image_bytes).decode('utf-8')
    
    url = f"https://generativelanguage.googleapis.com/v1beta/models/{model_name}:generateContent"
    headers = {"Content-Type": "application/json"}
    
    payload = {
        "contents": [{
            "parts": [
                {
                    "inline_data": {
                        "mime_type": "image/png",
                        "data": image_b64
                    }
                },
                {
                    "text": "Describe this Good Bald product in detail for creating a hero image scene."
                }
            ]
        }]
    }
    
    print(f"Testing basic Gemini: {model_name}...")
    response = requests.post(f"{url}?key={API_KEY}", headers=headers, json=payload)
    
    if response.status_code == 200:
        result = response.json()
        print("✅ Basic Gemini working!")
        
        if 'candidates' in result:
            text_content = result['candidates'][0]['content']['parts'][0]['text']
            print(f"Product description: {text_content[:200]}...")
        return True
    else:
        print(f"❌ Basic Gemini failed: {response.status_code}")
        print(response.text)
        return False

if __name__ == "__main__":
    print("🚀 Starting Good Bald hero image generation...")
    
    # First, let's check available models
    print("\n1. Checking available models...")
    models = list_available_models()
    
    # Try basic Gemini first to test connection
    print("\n2. Testing basic Gemini functionality...")
    basic_success = generate_with_basic_gemini()
    
    if basic_success:
        # Try Imagen for actual generation
        print("\n3. Attempting image generation with Imagen...")
        success = generate_with_imagen()
        
        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❌ Image generation failed")
            print("💡 The API might not support direct image generation yet")
            print("💡 Consider using alternative image generation services")
    else:
        print("\n❌ Basic API connection failed - check credentials")