import os
import re
from PIL import Image
from collections import defaultdict

RAIZ = "."  # pasta raiz
MAX_SIZE = 299 * 1024
IMG_EXTS = (".png", ".jpg", ".jpeg", ".webp", ".svg")

def otimizar_svg(path):
    try:
        with open(path, "r", encoding="utf-8") as f:
            svg_content = f.read()
        svg_content = re.sub(r"<!--.*?-->", "", svg_content, flags=re.DOTALL)
        svg_content = re.sub(r">\s+<", "><", svg_content)
        svg_content = re.sub(r"\s{2,}", " ", svg_content)
        temp_path = path.replace(".svg", "_temp.svg")
        with open(temp_path, "w", encoding="utf-8") as f:
            f.write(svg_content)
        new_size = os.path.getsize(temp_path)
        if new_size < os.path.getsize(path):
            os.replace(temp_path, path)
            print(f"✅ SVG otimizado: {path} → {new_size/1024:.1f} KB")
        else:
            os.remove(temp_path)
    except Exception as e:
        print(f"⚠️ Erro SVG {path}: {e}")

def otimizar_png(img_path):
    """Tenta reduzir PNG abaixo de MAX_SIZE sem mudar formato"""
    try:
        with Image.open(img_path) as img:
            # Tenta converter para paleta (modo P) para reduzir cores
            img = img.convert("P", palette=Image.ADAPTIVE)
            quality_steps = [9, 7, 5]  # compress_level progressivo
            for compress in quality_steps:
                temp_path = img_path.replace(".png", "_temp.png")
                img.save(temp_path, optimize=True, compress_level=compress)
                new_size = os.path.getsize(temp_path)
                if new_size <= MAX_SIZE:
                    os.replace(temp_path, img_path)
                    print(f"✅ PNG otimizado: {img_path} → {new_size/1024:.1f} KB")
                    return
            # Se ainda estiver grande, reduz dimensões
            width, height = img.size
            while new_size > MAX_SIZE and width > 100 and height > 100:
                width = int(width * 0.9)
                height = int(height * 0.9)
                img_resized = img.resize((width, height), Image.LANCZOS)
                img_resized.save(temp_path, optimize=True, compress_level=9)
                new_size = os.path.getsize(temp_path)
            os.replace(temp_path, img_path)
            print(f"✅ PNG redimensionado: {img_path} → {new_size/1024:.1f} KB")
    except Exception as e:
        print(f"⚠️ Erro PNG {img_path}: {e}")

def otimizar_imagem(img_path):
    ext = os.path.splitext(img_path)[1].lower()
    size = os.path.getsize(img_path)
    if size <= MAX_SIZE and ext != ".svg":
        return
    print(f"🔄 Processando {img_path} ({size/1024:.1f} KB)")
    if ext == ".svg":
        otimizar_svg(img_path)
    elif ext == ".png":
        otimizar_png(img_path)
    elif ext in (".jpg", ".jpeg"):
        try:
            with Image.open(img_path) as img:
                img = img.convert("RGB")
                quality = 90
                temp_path = img_path.replace(ext, "_temp.jpg")
                while True:
                    img.save(temp_path, "JPEG", quality=quality, optimize=True)
                    new_size = os.path.getsize(temp_path)
                    if new_size <= MAX_SIZE or quality <= 30:
                        os.replace(temp_path, img_path)
                        print(f"✅ JPG otimizado: {img_path} → {new_size/1024:.1f} KB")
                        break
                    quality -= 5
        except Exception as e:
            print(f"⚠️ Erro JPG {img_path}: {e}")
    elif ext == ".webp":
        try:
            with Image.open(img_path) as img:
                quality = 90
                temp_path = img_path.replace(".webp", "_temp.webp")
                while True:
                    img.save(temp_path, "WEBP", quality=quality, method=6)
                    new_size = os.path.getsize(temp_path)
                    if new_size <= MAX_SIZE or quality <= 30:
                        os.replace(temp_path, img_path)
                        print(f"✅ WEBP otimizado: {img_path} → {new_size/1024:.1f} KB")
                        break
                    quality -= 5
        except Exception as e:
            print(f"⚠️ Erro WEBP {img_path}: {e}")

# Agrupa arquivos pelo nome base
arquivos_por_nome = defaultdict(list)
for root, dirs, files in os.walk(RAIZ):
    for file in files:
        if file.lower().endswith(IMG_EXTS):
            caminho_completo = os.path.join(root, file)
            nome_base = os.path.splitext(file)[0]
            arquivos_por_nome[nome_base].append(caminho_completo)

# Processa arquivos acima de MAX_SIZE
for caminhos in arquivos_por_nome.values():
    for caminho in caminhos:
        tamanho = os.path.getsize(caminho)
        if tamanho > MAX_SIZE or caminho.lower().endswith(".svg"):
            otimizar_imagem(caminho)

print("✅ Otimização concluída!")
