#!/usr/bin/env python3
"""
Generate professional stock images for CleanKitchens using DALL-E 3
Version 2: Strict no people, no text except basic caution tape
"""

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
        }
        
        # STRICT style requirements - NO PEOPLE, NO TEXT
        self.style_base = "Professional photography of empty commercial kitchen, industrial setting, dramatic lighting, high contrast, cinematic quality, photorealistic, ABSOLUTELY NO PEOPLE, NO HUMAN FIGURES, NO SILHOUETTES, NO TEXT, NO WRITING, NO SIGNS WITH WORDS, NO FOREIGN LANGUAGE, plain yellow caution tape only if needed, no logos, no brands"
        
    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 - NO PEOPLE, NO TEXT"""
        return {
            'rodent': [
                f"Empty dark industrial kitchen corner with visible mouse droppings scattered on floor near stainless steel equipment, plain yellow caution tape stretched across area, {self.style_base}",
                f"Deserted commercial kitchen floor showing rat droppings and gnawed cardboard boxes, no text on boxes, dramatic shadows, {self.style_base}",
                f"Abandoned restaurant storage area with holes chewed in food containers, pest control bait stations visible, no labels or text, {self.style_base}",
                f"Empty industrial kitchen with mouse tracks in flour dust on stainless steel counter, overhead lighting, {self.style_base}"
            ],
            'roach': [
                f"Deserted commercial kitchen dark corner with cockroaches visible on stainless steel wall, plain yellow barrier tape, {self.style_base}",
                f"Empty industrial dishwashing area with dead roaches on floor, glue traps visible, harsh overhead lighting, {self.style_base}",
                f"Abandoned restaurant prep station with roach egg cases in crevices, dramatic shadows, no text visible, {self.style_base}",
                f"Vacant commercial kitchen showing roaches near floor drain, industrial lighting from above, {self.style_base}"
            ],
            'temperature': [
                f"Empty commercial refrigerator interior with digital thermometer display showing 55°F in red numbers only, frost buildup on walls, {self.style_base}",
                f"Deserted industrial kitchen with steam rising from overheated food warming station, red warning lights only no text, {self.style_base}",
                f"Abandoned walk-in cooler with ice crystals and condensation, temperature gauge showing red zone, numbers only no words, {self.style_base}",
                f"Empty commercial kitchen hot holding unit with visible temperature problems, steam and heat distortion, {self.style_base}"
            ],
            'cleanliness': [
                f"Grimy empty commercial kitchen with grease buildup on surfaces, plain yellow caution tape blocking area, harsh lighting, {self.style_base}",
                f"Deserted industrial dishwashing area with dirty standing water on floor, overhead dramatic lighting, {self.style_base}",
                f"Abandoned restaurant prep area with food debris and grime on surfaces, no text or signs visible, {self.style_base}",
                f"Empty commercial kitchen with clogged floor drains and accumulated dirt, industrial setting, {self.style_base}"
            ],
            'mold': [
                f"Dark empty commercial kitchen corner with black mold growth spreading on walls, moisture dripping, plain barrier tape, {self.style_base}",
                f"Deserted industrial refrigerator with fuzzy mold on rubber door seals, close-up detail, dramatic lighting, {self.style_base}",
                f"Abandoned restaurant with water-stained ceiling tiles showing mold growth, looking upward perspective, {self.style_base}",
                f"Empty walk-in cooler with green and black mold on walls, condensation visible, industrial lighting, {self.style_base}"
            ],
            'cross_contamination': [
                f"Empty commercial kitchen with raw chicken and vegetables on same cutting board, plain yellow tape dividing areas, {self.style_base}",
                f"Deserted prep area with raw meat dripping onto produce below, no labels or text visible, overhead view, {self.style_base}",
                f"Abandoned restaurant station with mixed raw and cooked foods stored together, dramatic angle, {self.style_base}",
                f"Empty industrial kitchen with improper food storage, raw above ready-to-eat, no text on containers, {self.style_base}"
            ],
            'handwashing': [
                f"Empty commercial kitchen with broken sink fixture, plain yellow caution tape across it, no signs with text, {self.style_base}",
                f"Deserted restaurant with empty soap dispensers and missing paper towels, industrial lighting, {self.style_base}",
                f"Abandoned handwashing station blocked by stacked boxes, no text on boxes, dramatic shadows, {self.style_base}",
                f"Empty industrial kitchen sink area with no soap or towels present, overhead harsh lighting, {self.style_base}"
            ],
            'structural': [
                f"Empty commercial kitchen with large hole in ceiling exposing pipes and wires, plain caution tape barriers, {self.style_base}",
                f"Deserted restaurant with severely cracked floor tiles creating trip hazards, dramatic angle, {self.style_base}",
                f"Abandoned industrial kitchen with broken equipment and exposed sharp edges, yellow tape only, {self.style_base}",
                f"Empty commercial space with collapsed ceiling tiles and water damage, no text visible, {self.style_base}"
            ],
            'sewage': [
                f"Empty commercial kitchen with dark water backing up from floor drain, plain yellow caution tape perimeter, {self.style_base}",
                f"Deserted restaurant with sewage overflow on floor, industrial lighting from above, no text or signs, {self.style_base}",
                f"Abandoned kitchen area with broken pipes leaking dark water, dramatic shadows, {self.style_base}",
                f"Empty dishwashing area with backed up drains and standing murky water, overhead lighting, {self.style_base}"
            ],
            'closure': [
                f"Locked glass restaurant door at night with red paper notice (no readable text), dramatic lighting through window, {self.style_base}",
                f"Empty darkened restaurant interior viewed through front window, plain yellow tape across door, evening light, {self.style_base}",
                f"Closed restaurant entrance with padlock and chain on handles, red tag attached but no text visible, {self.style_base}",
                f"Dark empty restaurant with chairs stacked on tables visible through window, yellow barrier tape on door, {self.style_base}",
                f"Shuttered restaurant storefront with metal grate down, plain red notice shape on door, dramatic shadows, {self.style_base}"
            ],
            'general': [
                f"Wide angle empty industrial kitchen with multiple plain yellow caution tape sections, dramatic overhead lighting, {self.style_base}",
                f"Deserted commercial restaurant kitchen with red tags on equipment but no text visible, professional angle, {self.style_base}",
                f"Abandoned stainless steel kitchen with inspection clipboard on counter (blank/no text), high contrast lighting, {self.style_base}",
                f"Empty restaurant prep area with plain colored violation tags on equipment, industrial aesthetic, {self.style_base}"
            ]
        }
    
    def get_chain_prompts(self):
        """Get prompts for chain restaurant images - NO PEOPLE"""
        return {
            'burger_chain': [
                f"Empty generic fast food burger kitchen with grill and fryer equipment, stainless steel surfaces, {self.style_base}",
                f"Deserted commercial burger station with flat-top grill and warming lamps, industrial ventilation, {self.style_base}",
                f"Abandoned fast food prep counter with burger assembly area, overhead lighting, {self.style_base}",
                f"Empty chain restaurant freezer with stacked unmarked boxes, commercial equipment, {self.style_base}"
            ],
            'coffee_chain': [
                f"Deserted commercial coffee shop with espresso machines and grinders, stainless steel counter, {self.style_base}",
                f"Empty coffee store prep area with syrup pumps and blenders, industrial setting, {self.style_base}",
                f"Abandoned coffee roasting area with commercial equipment, dramatic lighting, {self.style_base}",
                f"Vacant coffee shop storage with bags of beans (no labels), commercial shelving, {self.style_base}"
            ],
            'pizza_chain': [
                f"Empty industrial pizza kitchen with brick oven glowing, no branding visible, {self.style_base}",
                f"Deserted pizzeria prep station with dough mixer and ingredient containers (no labels), {self.style_base}",
                f"Abandoned commercial pizza kitchen with multiple deck ovens, industrial ventilation, {self.style_base}",
                f"Empty pizza restaurant cold storage with unmarked ingredient boxes, {self.style_base}"
            ],
            'chicken_chain': [
                f"Deserted industrial kitchen with commercial pressure fryers for chicken, stainless steel, {self.style_base}",
                f"Empty chain restaurant with breading station and fryer equipment, overhead lighting, {self.style_base}",
                f"Abandoned commercial chicken kitchen with multiple fryer units, industrial setting, {self.style_base}",
                f"Vacant fast food chicken prep area with freezers and thawing sinks, {self.style_base}"
            ]
        }
    
    def get_summary_prompts(self):
        """Get prompts for summary images - NO PEOPLE, MINIMAL TEXT"""
        return {
            'daily_summary': [
                f"Blank clipboard with inspection checklist grid (no text) on stainless steel surface, pen beside it, overhead lighting, {self.style_base}",
                f"Stack of blank inspection forms on industrial kitchen counter, dramatic angle, {self.style_base}",
                f"Digital tablet showing graph bars only (no text) in empty commercial kitchen setting, {self.style_base}",
                f"Red and green inspection grade cards (letter grades A, B, C only) arranged on metal surface, {self.style_base}",
                f"Inspector's toolkit with clipboard and thermometer on empty stainless steel table, professional angle, {self.style_base}"
            ],
            'weekly_summary': [
                f"Multiple blank inspection sheets spread on industrial surface, overhead view, dramatic lighting, {self.style_base}",
                f"Calendar grid with red X marks only (no text) in commercial kitchen setting, {self.style_base}",
                f"Series of colored grade cards (A, B, C, F only) showing progression, industrial background, {self.style_base}",
                f"Blank clipboard with bar chart drawn (no text) in empty kitchen, dramatic shadows, {self.style_base}",
                f"Digital screen showing pie chart only (no text) in deserted commercial kitchen, {self.style_base}"
            ]
        }
    
    def generate_image(self, prompt, category, index):
        """Generate a single image using DALL-E 3"""
        try:
            print(f"Generating {category}_{index}...")
            
            # Add extra safety prompt
            enhanced_prompt = prompt + " CRITICAL: Absolutely no people, no human figures, no cartoon characters, no human silhouettes, no text except single letters for grades or plain yellow caution tape, everything must be photorealistic not illustrated"
            
            response = self.client.images.generate(
                model="dall-e-3",
                prompt=enhanced_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': enhanced_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 V2...")
        print("STRICT: No people, no text except caution tape")
        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(),
            'version': 'v2_no_people_no_text',
            'stats': self.stats,
            'images': all_results
        }
        
        metadata_path = os.path.join(self.base_dir, 'generation_metadata_v2.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"""
    # Set API key
    os.environ['OPENAI_API_KEY'] = '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'
    
    generator = StockImageGenerator()
    
    print("This will generate ~100+ images with STRICT no people/no text policy")
    print("Cost: approximately $8-10")
    response = input("Proceed? (y/n): ")
    
    if response.lower() == 'y':
        generator.generate_all_images()
    else:
        print("Cancelled")

if __name__ == "__main__":
    main()