from PIL import Image
import os
import sys

def convert_to_webp(image_path):
    # Vérifier si le fichier existe
    if not os.path.isfile(image_path):
        print(f"Impossible de trouver {image_path}.")
        return

    # Charger l'image
    try:
        img = Image.open(image_path)
    except IOError:
        print(f"Impossible d'ouvrir {image_path}.")
        return
    
    max_width = 1024
    if img.width > max_width:
        # Calculer la nouvelle hauteur pour conserver le ratio d'aspect
        height = int((max_width / img.width) * img.height)
        img = img.resize((max_width, height), Image.Resampling.LANCZOS)



    output_path = os.path.splitext(image_path)[0] + '.webp'
    quality = 100 
    img.save(output_path, 'WEBP', quality=quality)
    
    
        # Supprimer l'ancienne image
    if not image_path.lower().endswith('.webp'):
        try:
            os.remove(image_path)
        except OSError:
            print(f"Impossible de supprimer l'ancienne image : {image_path}.")
 
    return output_path


# Exemple d'utilisation
# Remplacer 'chemin/vers/votre/image.jpg' par le chemin de votre image

if __name__ == '__main__':
        image_path = sys.argv[1]
        image_out = convert_to_webp(image_path)
        print (image_out)

