#!/usr/bin/env python3
"""
Generate remaining violation category images for CleanKitchens
"""

import os
import time
import requests
from pathlib import Path

# Load environment variables
from dotenv import load_dotenv
load_dotenv('/home/chris/.env')

# Image directory
image_dir = Path('/var/www/twin-digital-media/public_html/_sites/cleankitchens/assets/images/violations')

# Missing violation images we need to generate
MISSING_IMAGES = {
    # Missing general_2.jpg
    "general_2.jpg": "Professional commercial restaurant kitchen with stainless steel prep tables, organized cooking stations, and proper ventilation systems, bright and clean environment",
    
    # Missing structural_1.jpg, structural_3.jpg, structural_4.jpg
    "structural_1.jpg": "Restaurant interior showing proper structural maintenance with sound walls, ceilings, and floors in a professional kitchen environment",
    "structural_3.jpg": "Commercial kitchen with well-maintained structural elements, proper ceiling tiles, and professional flooring",
    "structural_4.jpg": "Restaurant dining area with properly maintained structural features, clean walls and professional appearance",
    
    # Sewage/plumbing images
    "plumbing_1.jpg": "Professional commercial kitchen sink and plumbing system, stainless steel fixtures with proper drainage",
    "plumbing_2.jpg": "Restaurant dish washing station with commercial-grade plumbing and sanitary equipment",
    "plumbing_3.jpg": "Clean commercial kitchen with proper plumbing infrastructure and drainage systems",
    "plumbing_4.jpg": "Professional restaurant prep sink area with stainless steel plumbing fixtures",
    
    # Lighting issues
    "lighting_1.jpg": "Well-lit commercial kitchen with proper overhead lighting and light shields over food preparation areas",
    "lighting_2.jpg": "Restaurant kitchen with adequate lighting fixtures and proper illumination for food safety",
    "lighting_3.jpg": "Professional kitchen showing proper lighting installation with protective covers",
    "lighting_4.jpg": "Commercial food preparation area with appropriate lighting and electrical safety measures",
    
    # Equipment/maintenance
    "equipment_1.jpg": "Commercial kitchen equipment in proper working condition, stainless steel appliances and machinery",
    "equipment_2.jpg": "Professional restaurant equipment maintenance area with clean, functioning appliances",
    "equipment_3.jpg": "Well-maintained commercial kitchen with properly functioning equipment and appliances",
    "equipment_4.jpg": "Restaurant kitchen showing clean, operational commercial equipment and proper maintenance",
    
    # Garbage/waste disposal
    "garbage_1.jpg": "Proper commercial garbage disposal area outside restaurant with covered dumpsters and clean surroundings",
    "garbage_2.jpg": "Clean restaurant waste management area with appropriate garbage containers and sanitary conditions",
    "garbage_3.jpg": "Professional waste disposal setup for commercial kitchen with proper containers",
    "garbage_4.jpg": "Well-organized restaurant garbage area with covered receptacles and clean environment",
}

def generate_dalle3_image(prompt, filename):
    """Generate image using DALL-E 3"""
    api_key = os.getenv('OPENAI_API_KEY')
    if not api_key:
        print("❌ OpenAI API key not found")
        return False
    
    print(f"🎨 Generating {filename}...")
    
    response = requests.post(
        "https://api.openai.com/v1/images/generations",
        headers={
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        },
        json={
            "model": "dall-e-3",
            "prompt": f"{prompt}, professional food service photography, clean and bright lighting, no people visible, high quality commercial photography style",
            "size": "1024x1024",
            "quality": "standard",
            "n": 1
        }
    )
    
    if response.status_code == 200:
        data = response.json()
        image_url = data['data'][0]['url']
        
        # Download the image
        img_response = requests.get(image_url)
        if img_response.status_code == 200:
            filepath = image_dir / filename
            with open(filepath, 'wb') as f:
                f.write(img_response.content)
            print(f"✅ Generated {filename}")
            return True
    
    print(f"❌ Failed to generate {filename}: {response.text}")
    return False

def main():
    print("🖼️  Generating remaining violation category images...")
    print(f"Target directory: {image_dir}")
    
    generated_count = 0
    total_cost = 0.0
    
    for filename, prompt in MISSING_IMAGES.items():
        filepath = image_dir / filename
        
        if filepath.exists():
            print(f"⏭️  Skipping {filename} (already exists)")
            continue
        
        if generate_dalle3_image(prompt, filename):
            generated_count += 1
            total_cost += 0.04  # DALL-E 3 cost per image
            
            # Rate limiting - DALL-E 3 has rate limits
            time.sleep(2)
        else:
            print(f"❌ Failed to generate {filename}")
    
    print(f"\n🎉 Generated {generated_count} images")
    print(f"💰 Total cost: ${total_cost:.2f}")
    
    # Now generate optimized versions
    print("\n🔄 Creating optimized versions...")
    os.system("cd /var/www/twin-digital-media/public_html/_sites/cleankitchens/assets/images && python3 optimize_images.py")

if __name__ == "__main__":
    main()