import os
import sys
from PIL import Image

def optimize_image(img_path, size=160, backup=False):
    if not os.path.exists(img_path):
        print(f"Error: {img_path} not found.")
        return

    src_path = img_path
    if backup:
        backup_path = img_path + ".orig"
        if not os.path.exists(backup_path):
            os.rename(img_path, backup_path)
            print(f"Backed up original to {backup_path}")
            src_path = backup_path
        else:
            src_path = backup_path

    try:
        img = Image.open(src_path)
        width, height = img.size
        print(f"Optimizing {img_path}: Original size {width}x{height}")

        # Crop to square
        crop_size = min(width, height)
        left = (width - crop_size) // 2
        
        if height > width:
            top = int((height - crop_size) * 0.15)
        else:
            top = (height - crop_size) // 2

        right = left + crop_size
        bottom = top + crop_size

        cropped = img.crop((left, top, right, bottom))
        resized = cropped.resize((size, size), Image.Resampling.LANCZOS)
        
        # Save as PNG
        resized.save(img_path, 'PNG', optimize=True)
        print(f"Saved optimized {size}x{size} image to {img_path}")
    except Exception as e:
        print(f"Error processing image: {e}")

if __name__ == '__main__':
    if len(sys.argv) > 1:
        optimize_image(sys.argv[1], backup=False)
    else:
        optimize_image('/root/Apps/Camila/public/assets/camila_prof.png', backup=True)
        optimize_image('/root/Apps/Camila/public/assets/kemily.png', backup=True)
