#!/usr/bin/env python3
"""
Generate 3 image variations for PHAT Foods investor deck "Problem" slide using Gemini
"""

import os
import sys
import requests
import json
import base64
from pathlib import Path

# Add the workspace to path to access any local modules
sys.path.append('/root/.openclaw/workspace')

def load_google_credentials():
    """Load Google credentials and get access token"""
    cred_path = "/root/.openclaw/workspace/google-auth/credentials.json"
    token_path = "/root/.openclaw/workspace/google-auth/token.json"
    
    if not os.path.exists(cred_path):
        raise FileNotFoundError("Google credentials not found")
    
    # For now, try to use environment variable or look for API key in common locations
    api_key = os.environ.get('GOOGLE_API_KEY') or os.environ.get('GEMINI_API_KEY')
    
    if not api_key:
        # Try to find API key in credentials files
        try:
            with open(cred_path, 'r') as f:
                creds = json.load(f)
                # Look for API key in various possible fields
                api_key = creds.get('api_key') or creds.get('gemini_api_key')
        except:
            pass
    
    if not api_key:
        # Try a different approach - look for any .env files or config files
        env_files = [
            '/root/.openclaw/workspace/.env',
            '/root/.openclaw/.env',
            '/root/.env'
        ]
        for env_file in env_files:
            if os.path.exists(env_file):
                with open(env_file, 'r') as f:
                    for line in f:
                        if 'GEMINI_API_KEY' in line or 'GOOGLE_API_KEY' in line:
                            api_key = line.split('=')[1].strip().strip('"\'')
                            break
                if api_key:
                    break
    
    return api_key

def generate_image_with_gemini(prompt, filename, api_key):
    """Generate image using Gemini API"""
    
    # Gemini 2.0 Flash with image generation
    url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-exp:generateContent?key={api_key}"
    
    payload = {
        "contents": [{
            "parts": [{
                "text": prompt
            }]
        }],
        "generationConfig": {
            "temperature": 0.7,
            "maxOutputTokens": 1024,
            "responseMimeType": "image/png"
        }
    }
    
    headers = {
        "Content-Type": "application/json"
    }
    
    try:
        response = requests.post(url, headers=headers, json=payload)
        response.raise_for_status()
        
        # If we get image data back, save it
        if response.headers.get('content-type', '').startswith('image/'):
            with open(filename, 'wb') as f:
                f.write(response.content)
            return True
        
        # Otherwise, try to parse JSON response that might contain base64 image
        result = response.json()
        if 'candidates' in result and result['candidates']:
            candidate = result['candidates'][0]
            if 'content' in candidate and 'parts' in candidate['content']:
                for part in candidate['content']['parts']:
                    if 'inlineData' in part:
                        # Base64 encoded image
                        image_data = base64.b64decode(part['inlineData']['data'])
                        with open(filename, 'wb') as f:
                            f.write(image_data)
                        return True
        
        print(f"Unexpected response format: {result}")
        return False
        
    except requests.exceptions.RequestException as e:
        print(f"API request failed: {e}")
        return False
    except Exception as e:
        print(f"Error processing response: {e}")
        return False

def main():
    """Generate the 3 image variations"""
    
    # Try to get API key
    try:
        api_key = load_google_credentials()
        if not api_key:
            print("No Gemini API key found. Trying alternate approach...")
            return False
    except Exception as e:
        print(f"Error loading credentials: {e}")
        return False
    
    # Image prompts for each variation
    prompts = {
        "problem_slide_v1.png": """
Create a high-quality editorial photograph in 16:9 landscape format. Close-up shot of a 5-year-old child's face showing subtle disappointment and confusion - NOT crying, just unimpressed. The child should have natural, warm lighting on their face with shallow depth of field. In the soft-focus foreground, show a birthday cake that looks "not quite right" - slightly deflated, with waxy-looking frosting that's an off-color, maybe too pale or artificial looking. The overall mood should be warm tones, natural lighting, editorial advertising quality similar to Oatly campaigns meets high-end food photography. NOT stock photo aesthetic. The disappointment should be subtle and relatable, not dramatic.
""",
        
        "problem_slide_v2.png": """
Create a high-quality editorial photograph in 16:9 landscape format. Wide shot of a 5-year-old child sitting at a birthday party table, looking sideways at a birthday cake with subtle confusion and disappointment. The cake should be the focal point - it looks like someone tried to make a birthday cake but something is clearly wrong: slightly deflated, wrong texture, waxy frosting that's an unnatural color. The setting should feel warm and inviting despite the disappointing cake. Natural lighting, shallow depth of field, warm tones. Editorial advertising quality - think Oatly campaign aesthetic meets high-end food photography. The child's expression should be subtle - more unimpressed than sad. NOT stock photo, NOT overly dramatic.
""",
        
        "problem_slide_v3.png": """
Create a high-quality editorial photograph in 16:9 landscape format. Detailed shot of a 5-year-old child's small hand poking at a birthday cake, clearly showing the cake's wrong texture - waxy, artificial-looking frosting, maybe slightly deflated or with an unnatural sheen. The texture should be obviously "not quite right" - the kind of frosting that feels wrong when touched. Shallow depth of field focusing on the hand and cake interaction, warm natural lighting, editorial advertising quality similar to Oatly campaigns meets high-end food photography. The image should convey the tactile disappointment of something that looks like it should be a cake but clearly isn't quite right. NOT stock photo aesthetic.
"""
    }
    
    output_dir = Path("/root/.openclaw/workspace/phat-deck-images")
    output_dir.mkdir(exist_ok=True)
    
    success_count = 0
    
    for filename, prompt in prompts.items():
        filepath = output_dir / filename
        print(f"Generating {filename}...")
        
        if generate_image_with_gemini(prompt, filepath, api_key):
            print(f"✓ Generated {filename}")
            success_count += 1
        else:
            print(f"✗ Failed to generate {filename}")
    
    print(f"\nGenerated {success_count}/3 images successfully")
    return success_count == 3

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)