#!/usr/bin/env python3
"""
Generate images using Grok API instead of OpenAI DALL-E
"""

import os
import requests
import json
import time
from typing import Optional, Dict, Any

class GrokImageGenerator:
    """Handle image generation using Grok API"""
    
    def __init__(self):
        self.api_key = os.getenv('GROK_API_KEY') or os.getenv('XAI_API_KEY')
        self.base_url = "https://api.x.ai/v1"
        
        if not self.api_key:
            raise ValueError("GROK_API_KEY or XAI_API_KEY not found in environment")
    
    def generate_image(self, 
                      prompt: str, 
                      model: str = "grok-2-vision-1212",
                      size: str = "1024x1024",
                      quality: str = "standard",
                      n: int = 1) -> Optional[Dict[str, Any]]:
        """
        Generate an image using Grok API
        
        Args:
            prompt: Text description of the image to generate
            model: Grok model to use (default: grok-2-vision-1212)
            size: Image size (1024x1024, 1792x1024, 1024x1792)
            quality: Image quality (standard or hd)
            n: Number of images to generate
            
        Returns:
            Dict with image data or None if failed
        """
        
        headers = {
            'Authorization': f'Bearer {self.api_key}',
            'Content-Type': 'application/json'
        }
        
        # Grok API request format
        data = {
            'model': model,
            'messages': [
                {
                    'role': 'user',
                    'content': f"Generate an image: {prompt}"
                }
            ],
            'temperature': 0.7,
            'max_tokens': 1024,
            'image_generation': {
                'enabled': True,
                'size': size,
                'quality': quality,
                'n': n
            }
        }
        
        try:
            print(f"🎨 Generating image with Grok API (model: {model})...")
            
            response = requests.post(
                f'{self.base_url}/chat/completions',
                headers=headers,
                json=data,
                timeout=60
            )
            
            if response.status_code == 200:
                result = response.json()
                
                # Extract image URL from Grok response
                if 'choices' in result and result['choices']:
                    # Grok might return the image URL in the message content
                    message = result['choices'][0].get('message', {})
                    
                    # Check for image attachments or URLs in the response
                    if 'images' in message:
                        return {
                            'success': True,
                            'images': message['images'],
                            'model': model
                        }
                    elif 'image_url' in message:
                        return {
                            'success': True,
                            'images': [{'url': message['image_url']}],
                            'model': model
                        }
                    else:
                        # Try to extract URL from content
                        content = message.get('content', '')
                        if 'http' in content:
                            # Extract URL from content
                            import re
                            urls = re.findall(r'https?://[^\s]+', content)
                            if urls:
                                return {
                                    'success': True,
                                    'images': [{'url': url} for url in urls],
                                    'model': model
                                }
                
                print("⚠️ No image URL found in Grok response")
                print(f"Response: {json.dumps(result, indent=2)}")
                return None
                
            else:
                print(f"❌ Grok API error: {response.status_code}")
                print(response.text)
                return None
                
        except requests.exceptions.Timeout:
            print("❌ Request timed out")
            return None
        except Exception as e:
            print(f"❌ Error: {e}")
            return None
    
    def download_and_save_image(self, image_url: str, output_path: str) -> bool:
        """
        Download and save an image from URL
        
        Args:
            image_url: URL of the image to download
            output_path: Path where to save the image
            
        Returns:
            True if successful, False otherwise
        """
        try:
            print(f"📸 Downloading image from: {image_url[:50]}...")
            
            response = requests.get(image_url, timeout=30)
            if response.status_code == 200:
                os.makedirs(os.path.dirname(output_path), exist_ok=True)
                
                with open(output_path, 'wb') as f:
                    f.write(response.content)
                
                print(f"✅ Image saved to: {output_path}")
                
                # Create WebP version for better performance
                try:
                    from PIL import Image
                    img = Image.open(output_path)
                    webp_path = output_path.replace('.jpg', '.webp').replace('.png', '.webp')
                    img.save(webp_path, 'WEBP', quality=85)
                    print(f"✅ WebP version saved to: {webp_path}")
                except ImportError:
                    print("⚠️ PIL not available, skipping WebP conversion")
                
                return True
            else:
                print(f"❌ Failed to download image: {response.status_code}")
                return False
                
        except Exception as e:
            print(f"❌ Error downloading image: {e}")
            return False


def generate_inspection_image():
    """Generate a professional inspection image using Grok API"""
    
    generator = GrokImageGenerator()
    
    # Professional inspection clipboard prompt
    prompt = """A photorealistic image of an official restaurant health inspection clipboard:
    - Clean white clipboard with metal clip at top
    - Header text reads 'HEALTH INSPECTION REPORT' in bold black letters
    - Visible checklist with items like 'Food Temperature', 'Hand Washing', 'Sanitation'
    - Some boxes checked with blue checkmarks
    - A blue pen attached to the clipboard
    - Clean white background
    - Professional, official government document style
    - High quality stock photo lighting
    - Sharp focus on clipboard, subtle shadow underneath"""
    
    result = generator.generate_image(
        prompt=prompt,
        size='1792x1024',
        quality='hd'
    )
    
    if result and result.get('success'):
        images = result.get('images', [])
        if images:
            image_url = images[0].get('url')
            if image_url:
                output_path = '/var/www/twin-digital-media/public_html/_sites/cleankitchens/assets/images/health-inspection-report-grok.jpg'
                if generator.download_and_save_image(image_url, output_path):
                    return output_path
    
    return None


def test_grok_connection():
    """Test the Grok API connection with a simple request"""
    
    try:
        generator = GrokImageGenerator()
        print("✅ Grok API key found")
        
        # Test with a simple prompt
        result = generator.generate_image(
            prompt="A simple test image of a blue circle on white background",
            size='1024x1024',
            quality='standard'
        )
        
        if result and result.get('success'):
            print("✅ Grok API connection successful")
            print(f"Model used: {result.get('model')}")
            return True
        else:
            print("❌ Failed to generate test image")
            return False
            
    except Exception as e:
        print(f"❌ Connection test failed: {e}")
        return False


if __name__ == "__main__":
    import sys
    
    if len(sys.argv) > 1 and sys.argv[1] == 'test':
        # Run connection test
        test_grok_connection()
    else:
        # Generate inspection image
        generate_inspection_image()