#!/usr/bin/env python3
"""
Optimize images for better compression and PageSpeed scores
"""

from PIL import Image
import os
from pathlib import Path

def optimize_image(image_path, quality=85):
    """Optimize a single image for web"""
    try:
        img = Image.open(image_path)
        
        # Convert RGBA to RGB if necessary
        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
        
        # Save with optimization
        img.save(image_path, 'JPEG', quality=quality, optimize=True, progressive=True)
        return True
    except Exception as e:
        print(f"Error optimizing {image_path}: {e}")
        return False

def create_optimized_versions(image_path):
    """Create optimized versions of an image with better compression"""
    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)
        
        # Convert RGBA to RGB if necessary
        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
        
        # Define size variants with more aggressive compression
        sizes = {
            'thumb': (400, 300, 75),     # quality 75 for thumbnails
            'og': (1200, 630, 80),        # quality 80 for Open Graph
            'twitter': (1024, 512, 80),   # quality 80 for Twitter
            'instagram': (1080, 1080, 82) # quality 82 for Instagram
        }
        
        for size_name, (width, height, quality) in sizes.items():
            # Create resized version
            img_resized = img.copy()
            
            # Calculate aspect ratio preserving dimensions
            img_ratio = img.width / img.height
            target_ratio = width / height
            
            if img_ratio > target_ratio:
                # Image is wider
                new_width = int(height * img_ratio)
                img_resized.thumbnail((new_width, height), Image.Resampling.LANCZOS)
            else:
                # Image is taller
                new_height = int(width / img_ratio)
                img_resized.thumbnail((width, new_height), Image.Resampling.LANCZOS)
            
            # Crop to exact dimensions
            left = (img_resized.width - width) / 2
            top = (img_resized.height - height) / 2
            right = (img_resized.width + width) / 2
            bottom = (img_resized.height + height) / 2
            img_resized = img_resized.crop((left, top, right, bottom))
            
            # Save as JPG with optimization
            jpg_path = optimized_dir / f"{base_name}_{size_name}.jpg"
            img_resized.save(jpg_path, 'JPEG', quality=quality, optimize=True, progressive=True)
            
            # Save as WebP with better compression
            webp_path = optimized_dir / f"{base_name}_{size_name}.webp"
            img_resized.save(webp_path, 'WEBP', quality=quality-5, method=6)  # More aggressive WebP compression
        
        # Also save original as optimized WebP
        webp_original = optimized_dir / f"{base_name}.webp"
        img.save(webp_original, 'WEBP', quality=80, method=6)
        
        # Save optimized JPG version
        jpg_optimized = optimized_dir / f"{base_name}_optimized.jpg"
        img.save(jpg_optimized, 'JPEG', quality=85, optimize=True, progressive=True)
        
        return True
        
    except Exception as e:
        print(f"Error creating optimized versions for {image_path}: {e}")
        return False

def main():
    base_dir = Path("/var/www/twin-digital-media/public_html/_sites/cleankitchens/assets/images")
    
    print("Optimizing images for better PageSpeed scores...")
    print("=" * 60)
    
    # Process violations images
    violations_dir = base_dir / "violations"
    if violations_dir.exists():
        print("\nOptimizing violation images...")
        for img_file in violations_dir.glob("*.jpg"):
            if "optimized" not in str(img_file):
                print(f"  Optimizing {img_file.name}")
                # Optimize the original
                optimize_image(img_file, quality=88)
                # Create optimized versions
                create_optimized_versions(img_file)
    
    # Process chains images
    chains_dir = base_dir / "chains"
    if chains_dir.exists():
        print("\nOptimizing chain images...")
        for img_file in chains_dir.glob("*.jpg"):
            if "optimized" not in str(img_file):
                print(f"  Optimizing {img_file.name}")
                # Optimize the original
                optimize_image(img_file, quality=88)
                # Create optimized versions
                create_optimized_versions(img_file)
    
    print("\n" + "=" * 60)
    print("Optimization complete!")
    print("Images are now optimized for better PageSpeed scores.")

if __name__ == "__main__":
    main()