#!/usr/bin/env python3
"""
Generate a professional restaurant inspection image using DALL-E 3
"""

import os
import requests
import json

def generate_inspection_image():
    """Generate a professional inspection image using DALL-E 3"""
    
    api_key = os.getenv('OPENAI_API_KEY')
    if not api_key:
        print("❌ OPENAI_API_KEY not found in environment")
        return
    
    # 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"""
    
    print("🎨 Generating professional inspection image with DALL-E 3...")
    
    headers = {
        'Authorization': f'Bearer {api_key}',
        'Content-Type': 'application/json'
    }
    
    data = {
        'model': 'dall-e-3',
        'prompt': prompt,
        'n': 1,
        'size': '1792x1024',
        'quality': 'hd',
        'style': 'natural'
    }
    
    try:
        response = requests.post(
            'https://api.openai.com/v1/images/generations',
            headers=headers,
            json=data
        )
        
        if response.status_code == 200:
            result = response.json()
            image_url = result['data'][0]['url']
            
            print(f"✅ Image generated successfully!")
            print(f"📸 Downloading image...")
            
            # Download the image
            img_response = requests.get(image_url)
            if img_response.status_code == 200:
                # Save the image
                output_path = '/var/www/twin-digital-media/public_html/_sites/cleankitchens/assets/images/health-inspection-report.jpg'
                os.makedirs(os.path.dirname(output_path), exist_ok=True)
                
                with open(output_path, 'wb') as f:
                    f.write(img_response.content)
                
                print(f"✅ Image saved to: {output_path}")
                
                # Also save as WebP for better performance
                from PIL import Image
                img = Image.open(output_path)
                webp_path = output_path.replace('.jpg', '.webp')
                img.save(webp_path, 'WEBP', quality=85)
                print(f"✅ WebP version saved to: {webp_path}")
                
                return output_path
            else:
                print(f"❌ Failed to download image: {img_response.status_code}")
                
        else:
            print(f"❌ DALL-E API error: {response.status_code}")
            print(response.text)
            
    except Exception as e:
        print(f"❌ Error: {e}")
        
    return None

if __name__ == "__main__":
    generate_inspection_image()