#!/usr/bin/env python3
"""
Optimize the DALL-E generated image for various sizes and formats
"""

from PIL import Image
import os

def optimize_inspection_image():
    """Create optimized versions of the DALL-E inspection image"""
    
    source_path = '/var/www/twin-digital-media/public_html/_sites/cleankitchens/assets/images/health-inspection-report.jpg'
    
    if not os.path.exists(source_path):
        print(f"❌ Source image not found: {source_path}")
        return
    
    print("🖼️ Optimizing DALL-E inspection image...")
    
    # Open the original image
    img = Image.open(source_path)
    
    # Create thumbnail version (600x400 for article cards)
    print("Creating thumbnail version...")
    thumb = img.copy()
    thumb.thumbnail((600, 400), Image.Resampling.LANCZOS)
    
    # Save compressed WebP thumbnail
    thumb_webp_path = source_path.replace('.jpg', '_thumb.webp')
    thumb.save(thumb_webp_path, 'WEBP', quality=75, method=6)
    print(f"✅ Thumbnail WebP saved: {thumb_webp_path}")
    
    # Save JPG thumbnail for fallback
    thumb_jpg_path = source_path.replace('.jpg', '_thumb.jpg')
    thumb.save(thumb_jpg_path, 'JPEG', quality=80, optimize=True)
    print(f"✅ Thumbnail JPG saved: {thumb_jpg_path}")
    
    # Create highly compressed page version
    print("Creating optimized page version...")
    page_webp_path = source_path.replace('.jpg', '_page.webp')
    img.save(page_webp_path, 'WEBP', quality=80, method=6)
    print(f"✅ Page WebP saved: {page_webp_path}")
    
    # Re-save the main WebP with better compression
    main_webp_path = source_path.replace('.jpg', '.webp')
    img.save(main_webp_path, 'WEBP', quality=82, method=6)
    print(f"✅ Main WebP re-saved with optimal compression")
    
    # Create social media versions with proper dimensions
    print("Creating social media versions...")
    
    # Open Graph (1200x630)
    og_img = img.copy()
    og_img.thumbnail((1200, 630), Image.Resampling.LANCZOS)
    og_path = source_path.replace('.jpg', '_og.jpg')
    og_img.save(og_path, 'JPEG', quality=85, optimize=True)
    print(f"✅ Open Graph version saved: {og_path}")
    
    # Twitter (1200x600)
    twitter_img = img.copy()
    twitter_img.thumbnail((1200, 600), Image.Resampling.LANCZOS)
    twitter_path = source_path.replace('.jpg', '_twitter.jpg')
    twitter_img.save(twitter_path, 'JPEG', quality=85, optimize=True)
    print(f"✅ Twitter version saved: {twitter_path}")
    
    print("\n✨ Optimization complete! All versions created.")
    
    # Show file sizes
    print("\n📊 File sizes:")
    for file in [source_path, main_webp_path, thumb_webp_path, page_webp_path]:
        if os.path.exists(file):
            size = os.path.getsize(file) / 1024
            print(f"  {os.path.basename(file)}: {size:.1f} KB")

if __name__ == "__main__":
    optimize_inspection_image()