#!/usr/bin/env python3
"""
Generate professional stock images using OpenAI DALL-E 3
With STRICT prompts to avoid any libelous or problematic content
"""

import os
import sys
import json
import time
import requests
from pathlib import Path
from openai import OpenAI
from PIL import Image
import io

# Load API key from home .env
from dotenv import load_dotenv
load_dotenv('/home/chris/.env')

client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))

# Base directory for images
BASE_DIR = Path("/var/www/twin-digital-media/public_html/_sites/cleankitchens/assets/images")

# STRICT PROFESSIONAL PROMPTS - NO PEOPLE, NO TEXT, NO BRAND NAMES
IMAGE_PROMPTS = {
    "violations": {
        "cleanliness": [
            "Sparkling clean commercial kitchen with stainless steel surfaces, bright professional lighting, empty space, no people, no text, no logos, professional architectural photography",
            "Pristine restaurant prep station with gleaming metal surfaces, bright overhead lighting, no people, no text, no signage, commercial photography style",
            "Ultra-clean commercial kitchen workspace, polished chrome fixtures, bright white lighting, no people, no text, no brands, professional real estate photography",
            "Immaculate restaurant kitchen area with shining equipment, bright natural light, no people, no text, no writing, architectural digest style"
        ],
        "temperature": [
            "Commercial refrigerator interior with bright LED lighting, empty clean shelves, stainless steel surfaces, no text, no labels, no people, professional equipment photography",
            "Restaurant kitchen heat lamps glowing warm orange over clean stainless steel pass, no people, no text, no signage, commercial photography",
            "Digital thermometer displaying temperature on clean surface, close-up shot, no people, no text except numbers, professional product photography",
            "Clean commercial freezer door slightly open showing frost-free interior, bright lighting, no people, no text, no brands, equipment photography"
        ],
        "handwashing": [
            "Clean commercial hand washing station with soap dispensers and paper towels, bright tiles, no people, no text, no signage, professional photography",
            "Restaurant kitchen sink area with automatic soap dispensers, bright lighting, no people, no text, no brands, commercial photography",
            "Professional kitchen hand washing area with multiple sinks, clean and bright, no people, no text, no writing, architectural photography",
            "Modern restaurant employee washing station, stainless steel fixtures, bright lighting, no people, no text, no logos, professional photography"
        ],
        "rodent": [
            "Exterior of modern restaurant building at dusk with warm lighting, professional architecture, no people, no text, no signage, real estate photography style",
            "Clean restaurant storage room with sealed containers on metal shelving, bright lighting, no people, no text, no brands, commercial photography",
            "Professional pest control equipment arranged neatly on white background, product photography style, no people, no text, no logos",
            "Restaurant exterior corner with professional landscaping, daylight, no people, no text, no signage, architectural photography"
        ],
        "roach": [
            "Clean restaurant floor drain with stainless steel grating, overhead view, bright lighting, no people, no text, no brands, professional photography",
            "Modern restaurant storage area with sealed bins, bright LED lighting, no people, no text, no signage, commercial photography",
            "Professional kitchen corner with baseboards and clean floors, bright lighting, no people, no text, no writing, architectural photography",
            "Restaurant supply closet interior, organized and clean, bright lighting, no people, no text, no logos, professional photography"
        ],
        "cross_contamination": [
            "Color-coded cutting boards arranged in professional kitchen, overhead view, bright lighting, no people, no text, professional culinary photography",
            "Separated prep stations in commercial kitchen, different colored zones, bright lighting, no people, no text, no signage, professional photography",
            "Restaurant kitchen with clearly divided work areas, bright and clean, no people, no text, no brands, architectural photography",
            "Professional knife storage with color-coded handles, close-up shot, no people, no text, no writing, product photography"
        ],
        "mold": [
            "Clean restaurant ceiling with ventilation system, bright lighting, no people, no text, no signage, architectural photography",
            "Restaurant wall corner showing clean painted surfaces, bright lighting, no people, no text, no brands, professional photography",
            "Commercial kitchen exhaust hood, clean stainless steel, bright lighting, no people, no text, no writing, equipment photography",
            "Restaurant storage area ceiling, clean and well-lit, no people, no text, no logos, architectural photography"
        ],
        "structural": [
            "Restaurant dining room ceiling with modern lighting fixtures, bright and clean, no people, no text, no signage, architectural photography",
            "Clean restaurant floor with professional tile pattern, bright lighting, no people, no text, no brands, commercial photography",
            "Modern restaurant wall with interesting architectural details, natural light, no people, no text, no writing, interior design photography",
            "Restaurant ventilation system in ceiling, clean industrial design, no people, no text, no logos, architectural photography"
        ],
        "sewage": [
            "Clean restaurant floor drain with modern grating, overhead view, bright lighting, no people, no text, no signage, professional photography",
            "Restaurant plumbing fixtures under sink, clean and organized, bright lighting, no people, no text, no brands, commercial photography",
            "Modern grease trap exterior, clean industrial equipment, bright lighting, no people, no text, no writing, equipment photography",
            "Clean utility area in restaurant, organized pipes and fixtures, no people, no text, no logos, architectural photography"
        ],
        "closure": [
            "Restaurant entrance with closed sign on door, professional photography, no people visible, minimal text only on sign, no brands",
            "Empty restaurant dining room through window, chairs on tables, no people, minimal signage, professional photography",
            "Restaurant storefront at night with lights off, professional architecture photography, no people, no text except existing signage",
            "Locked restaurant door with official notice posted, close-up shot, no people visible, minimal text, documentary style",
            "Restaurant exterior with barriers in front, professional photography, no people, no brands visible, neutral composition"
        ],
        "general": [
            "Modern restaurant interior overview, wide angle, bright lighting, no people, no text, no signage, architectural photography",
            "Generic restaurant kitchen overview, clean and professional, no people, no text, no brands, commercial photography",
            "Restaurant dining area with natural light, empty tables set, no people, no text, no writing, interior photography",
            "Professional restaurant entrance area, bright and welcoming, no people, no text, no logos, architectural photography"
        ]
    },
    "chains": {
        "burger_chain": [
            "Generic fast food restaurant interior with red and yellow color scheme, bright modern design, no people, no logos, no text, architectural photography",
            "Fast food restaurant counter area, bright colors, modern design, no people, no branding, no text, commercial photography",
            "Generic burger restaurant seating area with booth seats, bright lighting, no people, no text, no signage, interior photography",
            "Fast food restaurant kitchen visible through service window, clean and bright, no people, no text, no brands, professional photography"
        ],
        "coffee_chain": [
            "Modern coffee shop interior with warm lighting, generic design, no people, no text, no branding, architectural photography",
            "Coffee shop counter area with espresso machine visible, warm tones, no people, no logos, no text, commercial photography",
            "Generic cafe seating area with comfortable chairs, natural light, no people, no text, no signage, interior photography",
            "Coffee shop display case area, bright and clean, no people, no text, no brands, professional photography"
        ],
        "pizza_chain": [
            "Generic pizza restaurant with red checkered tablecloths, warm lighting, no people, no text, no logos, interior photography",
            "Pizza kitchen with brick oven visible, professional lighting, no people, no text, no branding, commercial photography",
            "Family pizza restaurant dining area, bright and cheerful, no people, no text, no signage, architectural photography",
            "Pizza restaurant counter with warming displays, bright lighting, no people, no text, no brands, professional photography"
        ],
        "chicken_chain": [
            "Generic fried chicken restaurant interior, orange and white colors, no people, no text, no logos, commercial photography",
            "Fast food chicken restaurant counter, bright modern design, no people, no text, no branding, architectural photography",
            "Chicken restaurant dining area with booth seating, warm lighting, no people, no text, no signage, interior photography",
            "Fast food restaurant with southern style decor, bright and clean, no people, no text, no brands, professional photography"
        ]
    }
}

def generate_image(prompt, save_path):
    """Generate a single image using DALL-E 3"""
    try:
        # Add strict safety suffix to every prompt
        safe_prompt = f"{prompt}. IMPORTANT: Absolutely no text, no words, no letters, no numbers, no signage with text, no logos, no brand names, no people, no faces. Professional photography only."
        
        print(f"  Generating: {save_path.name}")
        print(f"  Prompt: {safe_prompt[:100]}...")
        
        response = client.images.generate(
            model="dall-e-3",
            prompt=safe_prompt,
            size="1024x1024",
            quality="standard",
            n=1,
        )
        
        image_url = response.data[0].url
        
        # Download the image
        img_response = requests.get(image_url)
        img = Image.open(io.BytesIO(img_response.content))
        
        # Save as JPG
        img.save(save_path, 'JPEG', quality=95)
        
        print(f"  ✓ Saved to {save_path}")
        return True
        
    except Exception as e:
        print(f"  ✗ Error: {e}")
        return False

def create_optimized_versions(image_path):
    """Create optimized versions of an image"""
    try:
        img = Image.open(image_path)
        base_name = image_path.stem
        parent_dir = image_path.parent
        optimized_dir = parent_dir / "optimized"
        optimized_dir.mkdir(exist_ok=True)
        
        # Define size variants
        sizes = {
            'thumb': (400, 300),
            'og': (1200, 630),
            'twitter': (1024, 512),
            'instagram': (1080, 1080)
        }
        
        for size_name, dimensions in sizes.items():
            # Create resized version
            img_resized = img.copy()
            img_resized.thumbnail(dimensions, Image.Resampling.LANCZOS)
            
            # Save as JPG
            jpg_path = optimized_dir / f"{base_name}_{size_name}.jpg"
            img_resized.save(jpg_path, 'JPEG', quality=85)
            
            # Save as WebP
            webp_path = optimized_dir / f"{base_name}_{size_name}.webp"
            img_resized.save(webp_path, 'WEBP', quality=85)
        
        # Also save original as WebP
        webp_original = optimized_dir / f"{base_name}.webp"
        img.save(webp_original, 'WEBP', quality=90)
        
        print(f"    Created optimized versions for {base_name}")
        return True
        
    except Exception as e:
        print(f"    Error creating optimized versions: {e}")
        return False

def main():
    print("=" * 80)
    print("GENERATING PROFESSIONAL STOCK IMAGES WITH DALL-E 3")
    print("Using STRICT prompts: NO people, NO text, NO brands")
    print("=" * 80)
    
    total_images = 0
    total_cost = 0.0
    
    # Count total images needed
    for category, subcategories in IMAGE_PROMPTS.items():
        for subcat, prompts in subcategories.items():
            total_images += len(prompts)
    
    estimated_cost = total_images * 0.04  # DALL-E 3 costs $0.04 per image
    
    print(f"\nTotal images to generate: {total_images}")
    print(f"Estimated cost: ${estimated_cost:.2f}")
    print("\nStarting generation...\n")
    
    # Track progress
    generated = 0
    failed = 0
    
    # Generate violations images
    print("GENERATING VIOLATION IMAGES")
    print("-" * 40)
    
    violations_dir = BASE_DIR / "violations"
    violations_dir.mkdir(exist_ok=True)
    
    for violation_type, prompts in IMAGE_PROMPTS["violations"].items():
        print(f"\n{violation_type.upper()}:")
        for i, prompt in enumerate(prompts, 1):
            image_path = violations_dir / f"{violation_type}_{i}.jpg"
            
            if generate_image(prompt, image_path):
                generated += 1
                create_optimized_versions(image_path)
            else:
                failed += 1
            
            # Rate limiting - OpenAI allows 7 requests per minute for DALL-E 3
            time.sleep(9)  # Wait 9 seconds between requests
    
    # Generate chain images
    print("\n\nGENERATING CHAIN RESTAURANT IMAGES")
    print("-" * 40)
    
    chains_dir = BASE_DIR / "chains"
    chains_dir.mkdir(exist_ok=True)
    
    for chain_type, prompts in IMAGE_PROMPTS["chains"].items():
        print(f"\n{chain_type.upper()}:")
        for i, prompt in enumerate(prompts, 1):
            image_path = chains_dir / f"{chain_type}_{i}.jpg"
            
            if generate_image(prompt, image_path):
                generated += 1
                create_optimized_versions(image_path)
            else:
                failed += 1
            
            time.sleep(9)
    
    # Create metadata file
    metadata = {
        "generation_date": time.strftime("%Y-%m-%d %H:%M:%S"),
        "model": "dall-e-3",
        "total_generated": generated,
        "failed": failed,
        "estimated_cost": generated * 0.04,
        "safety_measures": [
            "No people in any images",
            "No text or signage with readable text",
            "No brand names or logos",
            "Professional photography style only",
            "Neutral, non-libelous content"
        ]
    }
    
    metadata_path = BASE_DIR / "generation_metadata_v2.json"
    with open(metadata_path, 'w') as f:
        json.dump(metadata, f, indent=2)
    
    print("\n" + "=" * 80)
    print("GENERATION COMPLETE")
    print(f"Successfully generated: {generated} images")
    print(f"Failed: {failed} images")
    print(f"Total cost: ${generated * 0.04:.2f}")
    print(f"Metadata saved to: {metadata_path}")
    print("=" * 80)

if __name__ == "__main__":
    # Check if we really want to proceed
    print("\n⚠️  WARNING: This will generate new images using OpenAI DALL-E 3")
    print(f"Estimated cost: ~$10-12 for all images")
    print("\nAll prompts are STRICTLY controlled to avoid:")
    print("  - Any people or faces")
    print("  - Any readable text or signage")
    print("  - Any brand names or logos")
    print("  - Any potentially libelous content")
    
    response = input("\nProceed with generation? (yes/no): ")
    if response.lower() == 'yes':
        main()
    else:
        print("Cancelled.")