#!/usr/bin/env python3
"""
Genera las fotos para el sitio a partir de las originales.

  villa-violeta/fotos/originales/*.jpg  →  sitio/public/assets/img/violeta/<nombre>-800.jpg y -1600.jpg
  villa-caleta/fotos/originales/*.jpg   →  sitio/public/assets/img/caleta/...
  compartido/fotos-playa-entorno/*.jpg  →  sitio/public/assets/img/compartido/...

Uso (desde la carpeta del proyecto):   python3 sitio/tools/optimizar_fotos.py
Requiere Pillow:                       pip install Pillow
Solo procesa fotos nuevas o modificadas. Para rehacer todo:  --todo
"""
import os
import re
import sys
from pathlib import Path

from PIL import Image, ImageOps

RAIZ = Path(os.path.abspath(__file__)).parents[2]
DESTINO = RAIZ / 'sitio' / 'public' / 'assets' / 'img'
FUENTES = {
    'violeta': RAIZ / 'villa-violeta' / 'fotos' / 'originales',
    'caleta': RAIZ / 'villa-caleta' / 'fotos' / 'originales',
    'compartido': RAIZ / 'compartido' / 'fotos-playa-entorno',
}
TAMANOS = (800, 1600)
CALIDAD = 78
EXT = {'.jpg', '.jpeg', '.png', '.webp'}


def slug(nombre: str) -> str:
    s = nombre.lower().strip()
    s = re.sub(r'[áàä]', 'a', s); s = re.sub(r'[éèë]', 'e', s); s = re.sub(r'[íìï]', 'i', s)
    s = re.sub(r'[óòö]', 'o', s); s = re.sub(r'[úùü]', 'u', s); s = s.replace('ñ', 'n')
    s = re.sub(r'[^a-z0-9]+', '-', s)
    return s.strip('-')


def main():
    todo = '--todo' in sys.argv
    hechas = 0
    for carpeta, origen in FUENTES.items():
        if not origen.is_dir():
            continue
        salida = DESTINO / carpeta
        salida.mkdir(parents=True, exist_ok=True)
        for f in sorted(origen.iterdir()):
            if f.suffix.lower() not in EXT or f.name.startswith('.'):
                continue
            base = slug(f.stem)
            objetivos = [salida / f'{base}-{t}.jpg' for t in TAMANOS]
            if not todo and all(o.exists() and o.stat().st_mtime >= f.stat().st_mtime for o in objetivos):
                continue
            im = ImageOps.exif_transpose(Image.open(f)).convert('RGB')
            for t, o in zip(TAMANOS, objetivos):
                copia = im.copy()
                copia.thumbnail((t, t), Image.LANCZOS)
                copia.save(o, 'JPEG', quality=CALIDAD, optimize=True, progressive=True)
            hechas += 1
            print(f'  {carpeta}/{base}')
    print(f'Listo: {hechas} foto(s) procesada(s).')


if __name__ == '__main__':
    main()
