import os
from PIL import Image

dir_path = 'public/sitio'
images = [
    'drpablogonzalezcima.png',
    'drnalasouilhe.png',
    'draelianatrassani.png',
    'dravictoriatejedor.png'
]

max_width = 800

for filename in images:
    filepath = os.path.join(dir_path, filename)
    if not os.path.exists(filepath):
        print(f"File {filepath} not found, skipping.")
        continue
    
    before_size = os.path.getsize(filepath)
    
    try:
        with Image.open(filepath) as img:
            # Calculate height to maintain aspect ratio
            w, h = img.size
            if w > max_width:
                new_h = int(h * (max_width / w))
                img_resized = img.resize((max_width, new_h), Image.Resampling.LANCZOS)
                print(f"Resized {filename} from {w}x{h} to {max_width}x{new_h}")
            else:
                img_resized = img
                print(f"No resizing needed for {filename} ({w}x{h})")
            
            # Save as WebP
            output_filename = os.path.splitext(filename)[0] + '.webp'
            output_path = os.path.join(dir_path, output_filename)
            
            img_resized.save(output_path, 'WEBP', quality=85)
            
            after_size = os.path.getsize(output_path)
            reduction = (before_size - after_size) / before_size * 100
            print(f"Saved {output_filename}: {before_size/1024/1024:.2f} MB -> {after_size/1024:.2f} KB ({reduction:.1f}% reduction)\n")
            
    except Exception as e:
        print(f"Error processing {filename}: {e}\n")
