#!/usr/bin/env python3
"""
Generate ONLY the images needed for homepage with PROFESSIONAL restaurant prompts
STRICT SAFETY: No people, no text, no brands, no libel risk
"""

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

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

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

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

# VERY SPECIFIC PROFESSIONAL RESTAURANT PROMPTS
# Based on actual restaurant inspection scenarios but SAFE and PROFESSIONAL
HOMEPAGE_IMAGES = {
    "general_1.jpg": "Professional commercial restaurant kitchen with stainless steel equipment, bright overhead lighting, pristine condition, modern industrial design, no people, no text, no signage, architectural photography style",
    
    "general_3.jpg": "Upscale restaurant dining room with empty tables set with white tablecloths, warm ambient lighting, elegant interior design, no people, no text, no branding, fine dining atmosphere",
    
    "general_4.jpg": "Modern restaurant bar area with clean countertops, pendant lighting, organized glassware displays, professional hospitality design, no people, no text, no logos, commercial photography",
    
    "cleanliness_4.jpg": "Immaculate commercial kitchen prep station with gleaming stainless steel surfaces, bright LED lighting, spotless workspace, professional food service equipment, no people, no text, no signage",
    
    "handwashing_4.jpg": "Commercial restaurant hand washing station with multiple sinks, automatic soap dispensers, bright tile walls, professional sanitation area, no people, no text, no branding",
    
    "rodent_2.jpg": "Professional restaurant dry storage room with organized shelving, sealed food containers, bright fluorescent lighting, clean industrial flooring, no people, no text, no labels visible",
    
    "structural_2.jpg": "Restaurant dining room ceiling showing modern HVAC system and lighting fixtures, clean architectural details, professional interior design, no people, no text, no signage"
}

def generate_image(prompt, save_path):
    """Generate a single professional restaurant image"""
    try:
        # Add strict safety measures to every prompt
        safe_prompt = f"{prompt}. CRITICAL: Absolutely no people, no faces, no text, no words, no signage, no logos, no brand names visible anywhere. Professional restaurant photography only. Clean, bright, upscale appearance."
        
        print(f"Generating: {save_path.name}")
        print(f"Prompt: {safe_prompt[:80]}...")
        
        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 with high quality
        img.save(save_path, 'JPEG', quality=95)
        
        print(f"✓ Successfully saved: {save_path}")
        return True
        
    except Exception as e:
        print(f"✗ Error generating {save_path.name}: {e}")
        return False

def create_optimized_versions(image_path):
    """Create optimized versions for web"""
    try:
        img = Image.open(image_path)
        base_name = image_path.stem
        optimized_dir = image_path.parent / "optimized"
        optimized_dir.mkdir(exist_ok=True)
        
        # Convert RGBA to RGB if needed
        if img.mode == 'RGBA':
            rgb_img = Image.new('RGB', img.size, (255, 255, 255))
            rgb_img.paste(img, mask=img.split()[3])
            img = rgb_img
        
        # Create web-optimized versions
        sizes = {
            'thumb': (400, 300, 75),
            'og': (1200, 630, 80),
            'twitter': (1024, 512, 80),
            'instagram': (1080, 1080, 82)
        }
        
        for size_name, (width, height, quality) in sizes.items():
            img_resized = img.copy()
            img_resized.thumbnail((width, height), Image.Resampling.LANCZOS)
            
            # Save as JPG
            jpg_path = optimized_dir / f"{base_name}_{size_name}.jpg"
            img_resized.save(jpg_path, 'JPEG', quality=quality, optimize=True)
            
            # Save as WebP
            webp_path = optimized_dir / f"{base_name}_{size_name}.webp"
            img_resized.save(webp_path, 'WEBP', quality=quality-5)
        
        # Original as WebP
        webp_original = optimized_dir / f"{base_name}.webp"
        img.save(webp_original, 'WEBP', quality=85)
        
        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 HOMEPAGE IMAGES - PROFESSIONAL RESTAURANT PHOTOGRAPHY")
    print("STRICT SAFETY: No people, no text, no brands, no libel risk")
    print("=" * 80)
    
    total_cost = len(HOMEPAGE_IMAGES) * 0.04
    print(f"\nImages to generate: {len(HOMEPAGE_IMAGES)}")
    print(f"Estimated cost: ${total_cost:.2f}")
    
    generated = 0
    failed = 0
    
    for filename, prompt in HOMEPAGE_IMAGES.items():
        image_path = BASE_DIR / filename
        
        print(f"\n[{generated + failed + 1}/{len(HOMEPAGE_IMAGES)}]")
        
        if generate_image(prompt, image_path):
            generated += 1
            create_optimized_versions(image_path)
        else:
            failed += 1
        
        # Rate limiting - wait between requests
        if generated + failed < len(HOMEPAGE_IMAGES):
            print("  Waiting 10 seconds...")
            time.sleep(10)
    
    print("\n" + "=" * 80)
    print("HOMEPAGE IMAGE GENERATION COMPLETE")
    print(f"Successfully generated: {generated}")
    print(f"Failed: {failed}")
    print(f"Total cost: ${generated * 0.04:.2f}")
    print("=" * 80)

if __name__ == "__main__":
    print("\n⚠️  GENERATING PROFESSIONAL HOMEPAGE IMAGES")
    print("All prompts are restaurant-focused and libel-safe")
    print("- No people or faces")
    print("- No text or signage") 
    print("- No brand names")
    print("- Professional restaurant photography only")
    
    response = input(f"\nGenerate {len(HOMEPAGE_IMAGES)} homepage images? (yes/no): ")
    if response.lower() == 'yes':
        main()
    else:
        print("Cancelled.")