#!/usr/bin/env python3
"""
Generate professional stock images for CleanKitchens using DALL-E 3
Industrial, realistic style with caution tape, commercial kitchens, violations
"""

import os
import json
import time
import requests
from openai import OpenAI
from datetime import datetime

class StockImageGenerator:
    def __init__(self):
        # OpenAI configuration
        self.client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
        
        # Base directory for images
        self.base_dir = '/var/www/twin-digital-media/public_html/_sites/cleankitchens/assets/images'
        
        # Image generation settings
        self.image_size = "1792x1024"  # Wide format for articles
        self.quality = "hd"
        
        # Track generation stats
        self.stats = {
            'generated': 0,
            'failed': 0,
            'total_cost': 0  # HD images cost $0.080 each
        }
        
        # Professional style prompt base
        self.style_base = "Professional photography, industrial commercial kitchen setting, dramatic lighting, high contrast, cinematic quality, photorealistic, no people, no text, no logos"
        
    def create_directories(self):
        """Create directory structure for images"""
        categories = ['violations', 'chains', 'cuisine', 'summaries']
        
        for category in categories:
            path = os.path.join(self.base_dir, category)
            os.makedirs(path, exist_ok=True)
            print(f"Created directory: {path}")
    
    def get_violation_prompts(self):
        """Get prompts for violation images"""
        return {
            'rodent': [
                f"Dark industrial kitchen corner with visible mouse droppings near food prep area, yellow caution tape in foreground, {self.style_base}",
                f"Commercial kitchen floor with rat shadows and gnawed food packaging, warning signs visible, {self.style_base}",
                f"Stainless steel kitchen shelving with rodent evidence, pest control boxes, dramatic shadows, {self.style_base}",
                f"Restaurant storage area with compromised food containers showing rodent damage, industrial lighting, {self.style_base}"
            ],
            'roach': [
                f"Commercial kitchen dark corner with cockroach silhouettes on stainless steel, caution tape, {self.style_base}",
                f"Industrial dishwashing area with pest evidence, dramatic overhead lighting, warning signs, {self.style_base}",
                f"Restaurant prep station with insect traps and warning indicators, high contrast lighting, {self.style_base}",
                f"Dark commercial kitchen crevices with pest activity indicators, professional inspection lighting, {self.style_base}"
            ],
            'temperature': [
                f"Commercial refrigerator with digital thermometer showing danger zone temperature, red warning lights, {self.style_base}",
                f"Industrial kitchen heat lamp station with temperature violation indicators, steam and condensation, {self.style_base}",
                f"Walk-in cooler with frost buildup and temperature gauge in red zone, caution signage, {self.style_base}",
                f"Stainless steel food warming station with visible temperature problems, warning tape, {self.style_base}"
            ],
            'cleanliness': [
                f"Grimy commercial kitchen surfaces with visible buildup, harsh inspection lighting, caution tape, {self.style_base}",
                f"Dirty industrial dishwashing area with standing water, overhead dramatic lighting, {self.style_base}",
                f"Neglected restaurant prep area with accumulated debris, warning signs posted, {self.style_base}",
                f"Commercial kitchen floor drains with visible contamination, industrial setting, {self.style_base}"
            ],
            'mold': [
                f"Dark commercial kitchen corner with visible mold growth on walls, moisture damage, warning tape, {self.style_base}",
                f"Industrial refrigerator seals with black mold, close-up detail, dramatic lighting, {self.style_base}",
                f"Restaurant ceiling tiles with water damage and mold stains, looking up perspective, {self.style_base}",
                f"Walk-in cooler with mold on surfaces, condensation visible, industrial lighting, {self.style_base}"
            ],
            'cross_contamination': [
                f"Commercial cutting boards with raw and cooked foods dangerously close, warning indicators, {self.style_base}",
                f"Industrial kitchen prep area with improper food storage, color-coded violation markers, {self.style_base}",
                f"Restaurant work station showing contamination risks, caution tape sectioning areas, {self.style_base}",
                f"Stainless steel surfaces with mixed food preparation hazards, overhead warning lights, {self.style_base}"
            ],
            'handwashing': [
                f"Broken commercial sink in industrial kitchen, caution tape across it, dramatic shadows, {self.style_base}",
                f"Empty soap dispensers and paper towel holders in restaurant washroom, warning signs, {self.style_base}",
                f"Blocked handwashing station with supplies stored in sink, violation notice posted, {self.style_base}",
                f"Industrial kitchen with missing handwashing supplies, inspection checklist visible, {self.style_base}"
            ],
            'structural': [
                f"Damaged commercial kitchen ceiling with exposed infrastructure, caution tape barriers, {self.style_base}",
                f"Cracked restaurant floor tiles with safety hazards marked, industrial lighting, {self.style_base}",
                f"Broken industrial kitchen equipment with warning tags, dramatic angle, {self.style_base}",
                f"Restaurant wall damage with exposed areas, temporary barriers, construction lighting, {self.style_base}"
            ],
            'sewage': [
                f"Commercial floor drain backup in industrial kitchen, warning cones placed, {self.style_base}",
                f"Restaurant basement with water damage indicators, caution tape barriers, harsh lighting, {self.style_base}",
                f"Industrial kitchen with plumbing issues visible, warning signs posted, {self.style_base}",
                f"Commercial dishwashing area with drainage problems, standing water, warning markers, {self.style_base}"
            ],
            'closure': [
                f"Restaurant entrance with official red closure notice on door, dramatic evening lighting, {self.style_base}",
                f"Commercial kitchen with red tags on all equipment, caution tape across entrance, {self.style_base}",
                f"Locked restaurant doors with health department closure signs, reflective glass, {self.style_base}",
                f"Dark restaurant interior visible through window with closure notice prominent, {self.style_base}",
                f"Yellow caution tape across restaurant entrance with official notices, dramatic shadows, {self.style_base}"
            ],
            'general': [
                f"Wide angle industrial kitchen with multiple violation indicators, caution tape, dramatic lighting, {self.style_base}",
                f"Commercial restaurant kitchen under inspection, warning signs visible, professional photography, {self.style_base}",
                f"Stainless steel commercial kitchen with health code violation markers, industrial aesthetic, {self.style_base}",
                f"Restaurant prep area with inspection tags and warnings, high contrast lighting, {self.style_base}"
            ]
        }
    
    def get_chain_prompts(self):
        """Get prompts for chain restaurant images"""
        return {
            'burger_chain': [
                f"Generic fast food burger restaurant kitchen, industrial fryer area, stainless steel surfaces, {self.style_base}",
                f"Commercial burger grill station with ventilation hoods, professional kitchen lighting, {self.style_base}",
                f"Fast food prep area with burger assembly line, industrial setting, {self.style_base}",
                f"Chain restaurant freezer with burger supplies, commercial equipment visible, {self.style_base}"
            ],
            'coffee_chain': [
                f"Commercial coffee shop equipment area, espresso machines, industrial counter, {self.style_base}",
                f"Chain coffee store prep area with syrups and supplies, stainless steel surfaces, {self.style_base}",
                f"Industrial coffee roasting equipment in commercial setting, dramatic lighting, {self.style_base}",
                f"Coffee chain storage area with beans and supplies, commercial shelving, {self.style_base}"
            ],
            'pizza_chain': [
                f"Industrial pizza oven in commercial kitchen, high temperature equipment, {self.style_base}",
                f"Chain pizzeria prep station with dough and toppings, stainless steel surfaces, {self.style_base}",
                f"Commercial pizza kitchen with multiple ovens, industrial ventilation, {self.style_base}",
                f"Pizza chain refrigeration units with ingredients, commercial storage, {self.style_base}"
            ],
            'chicken_chain': [
                f"Industrial deep fryer station for chicken, commercial kitchen setting, {self.style_base}",
                f"Chain restaurant chicken prep area, breading station, stainless steel, {self.style_base}",
                f"Commercial pressure fryer equipment, industrial chicken kitchen, {self.style_base}",
                f"Fast food chicken storage freezers, commercial equipment, {self.style_base}"
            ]
        }
    
    def get_summary_prompts(self):
        """Get prompts for summary images"""
        return {
            'daily_summary': [
                f"Clipboard with inspection checklist on stainless steel surface, dramatic overhead lighting, {self.style_base}",
                f"Health inspection grade cards arranged on industrial surface, professional photography, {self.style_base}",
                f"Digital tablet showing inspection data in commercial kitchen setting, {self.style_base}",
                f"Stack of violation notices on industrial kitchen counter, dramatic lighting, {self.style_base}",
                f"Inspector's toolkit and reports on stainless steel table, professional angle, {self.style_base}"
            ],
            'weekly_summary': [
                f"Multiple inspection reports spread on industrial surface, overhead view, {self.style_base}",
                f"Week calendar with violation markers in commercial setting, dramatic lighting, {self.style_base}",
                f"Series of health grade cards showing weekly progression, industrial background, {self.style_base}",
                f"Inspection clipboard with weekly summary charts, commercial kitchen backdrop, {self.style_base}",
                f"Digital display showing weekly violation statistics, industrial setting, {self.style_base}"
            ]
        }
    
    def generate_image(self, prompt, category, index):
        """Generate a single image using DALL-E 3"""
        try:
            print(f"Generating {category}_{index}...")
            
            response = self.client.images.generate(
                model="dall-e-3",
                prompt=prompt,
                size=self.image_size,
                quality=self.quality,
                n=1
            )
            
            # Get image URL
            image_url = response.data[0].url
            
            # Download image
            img_response = requests.get(image_url)
            if img_response.status_code == 200:
                # Determine subfolder
                if category in ['rodent', 'roach', 'temperature', 'cleanliness', 'mold', 
                               'cross_contamination', 'handwashing', 'structural', 
                               'sewage', 'closure', 'general']:
                    subfolder = 'violations'
                elif '_chain' in category:
                    subfolder = 'chains'
                elif '_summary' in category:
                    subfolder = 'summaries'
                else:
                    subfolder = 'general'
                
                # Save image
                filename = f"{category}_{index}.jpg"
                filepath = os.path.join(self.base_dir, subfolder, filename)
                
                with open(filepath, 'wb') as f:
                    f.write(img_response.content)
                
                print(f"✓ Saved: {filepath}")
                self.stats['generated'] += 1
                self.stats['total_cost'] += 0.08  # HD image cost
                
                return {
                    'category': category,
                    'filename': filename,
                    'subfolder': subfolder,
                    'filepath': filepath,
                    'prompt': prompt
                }
            
        except Exception as e:
            print(f"✗ Failed to generate {category}_{index}: {e}")
            self.stats['failed'] += 1
            return None
        
        # Rate limiting
        time.sleep(2)  # Be nice to the API
    
    def generate_category(self, category_name, prompts):
        """Generate all images for a category"""
        results = []
        
        print(f"\n=== Generating {category_name} images ===")
        
        for i, prompt in enumerate(prompts, 1):
            result = self.generate_image(prompt, category_name, i)
            if result:
                results.append(result)
        
        return results
    
    def generate_all_images(self):
        """Generate all stock images"""
        print("Starting CleanKitchens stock image generation...")
        print(f"Image size: {self.image_size}")
        print(f"Quality: {self.quality}")
        
        # Create directories
        self.create_directories()
        
        all_results = []
        
        # Generate violation images
        violation_prompts = self.get_violation_prompts()
        for category, prompts in violation_prompts.items():
            results = self.generate_category(category, prompts)
            all_results.extend(results)
        
        # Generate chain images
        chain_prompts = self.get_chain_prompts()
        for category, prompts in chain_prompts.items():
            results = self.generate_category(category, prompts)
            all_results.extend(results)
        
        # Generate summary images
        summary_prompts = self.get_summary_prompts()
        for category, prompts in summary_prompts.items():
            results = self.generate_category(category, prompts)
            all_results.extend(results)
        
        # Save metadata
        metadata = {
            'generated_at': datetime.now().isoformat(),
            'stats': self.stats,
            'images': all_results
        }
        
        metadata_path = os.path.join(self.base_dir, 'generation_metadata.json')
        with open(metadata_path, 'w') as f:
            json.dump(metadata, f, indent=2)
        
        print(f"\n=== Generation Complete ===")
        print(f"Generated: {self.stats['generated']} images")
        print(f"Failed: {self.stats['failed']} images")
        print(f"Total cost: ${self.stats['total_cost']:.2f}")
        print(f"Metadata saved to: {metadata_path}")
        
        return all_results

def main():
    """Main execution"""
    # Check for API key
    if not os.getenv('OPENAI_API_KEY'):
        print("Error: OPENAI_API_KEY environment variable not set")
        print("Run: export OPENAI_API_KEY='your-key-here'")
        return
    
    generator = StockImageGenerator()
    
    print("This will generate ~100+ images and cost approximately $8-10")
    response = input("Proceed? (y/n): ")
    
    if response.lower() == 'y':
        generator.generate_all_images()
    else:
        print("Cancelled")

if __name__ == "__main__":
    main()