import os
from PIL import Image

def optimize_to_webp(directory="."):
    print("🚀 Pokrećem lokalni WebP kompresor...\n")
    
    # Prolazimo kroz sve fajlove u folderu
    for filename in os.listdir(directory):
        if filename.lower().endswith((".png", ".jpg", ".jpeg")):
            filepath = os.path.join(directory, filename)
            
            try:
                with Image.open(filepath) as img:
                    width, height = img.size
                    
                    # Naša serverska logika kompresije
                    quality = 85 if width > 1400 else 70
                    
                    # Kreiranje novog imena
                    base_name = os.path.splitext(filename)[0]
                    webp_filepath = os.path.join(directory, f"{base_name}.webp")
                    
                    # Čuvanje u WebP formatu
                    img.save(webp_filepath, "WEBP", quality=quality)
                    
                # Obrisali smo os.remove(filepath) - originali ostaju netaknuti!
                
                print(f"✅ Kreirano: {base_name}.webp (Quality: {quality}) | Original sačuvan.")
                
            except Exception as e:
                print(f"❌ Greška pri obradi {filename}: {e}")

if __name__ == "__main__":
    optimize_to_webp()
    print("\nSve slike su 'squoosh'-ovane, a originali su na sigurnom! 😎")