import os
from PIL import Image

PASTA_RAIZ = os.path.dirname(os.path.abspath(__file__))
EXTENSOES = {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif"}

total = 0
erros = 0

for raiz, dirs, arquivos in os.walk(PASTA_RAIZ):
    for nome in arquivos:
        ext = os.path.splitext(nome)[1].lower()
        if ext not in EXTENSOES:
            continue

        caminho = os.path.join(raiz, nome)
        try:
            with Image.open(caminho) as img:
                largura, altura = img.size
                nova_largura = largura // 2
                nova_altura = altura // 2

                if nova_largura < 1 or nova_altura < 1:
                    continue

                img_reduzida = img.resize((nova_largura, nova_altura), Image.LANCZOS)
                img_reduzida.save(caminho, optimize=True)
                total += 1
                rel = os.path.relpath(caminho, PASTA_RAIZ)
                print(f"[OK] {rel}  {largura}x{altura} -> {nova_largura}x{nova_altura}")
        except Exception as e:
            erros += 1
            print(f"[ERRO] {caminho}: {e}")

print(f"\nConcluido! {total} imagens reduzidas, {erros} erros.")
