#!/usr/bin/env python3
"""Compresse les images de public/img/categories/ et convertit en WEBP.

Usage :
    python cli/optimize-category-images.py           # applique
    python cli/optimize-category-images.py --dry-run # simule

Strategie :
- Resize "contain" max 800x600 (ratio preserve, jamais agrandi)
- Re-encode en WEBP qualite 80, method=6 (best compression)
- Supprime l'original si different (jpg/png -> webp)

Pre-requis : Pillow (`pip install Pillow`).
"""
from pathlib import Path
from PIL import Image
import sys

DIR = Path(__file__).resolve().parent.parent / "public" / "img" / "categories"
MAX_W, MAX_H = 800, 600
QUALITY = 80

dry_run = "--dry-run" in sys.argv

if not DIR.is_dir():
    print(f"Dossier introuvable : {DIR}", file=sys.stderr)
    sys.exit(1)

files = sorted(
    f for f in DIR.iterdir()
    if f.is_file() and f.suffix.lower() in (".jpg", ".jpeg", ".webp", ".png")
)

total = len(files)
orig_size = 0
new_size = 0
skipped = 0

print(f"Trouve {total} image(s).")
if dry_run:
    print("MODE DRY-RUN - aucune ecriture en disque.")
print(f"Cible : WEBP qualite {QUALITY}, max {MAX_W}x{MAX_H}")
print("-" * 78)

for source in files:
    try:
        img = Image.open(source)
        img.load()
    except Exception as e:
        print(f"  SKIP {source.name} : {e}")
        skipped += 1
        continue

    w, h = img.size
    orig_bytes = source.stat().st_size
    orig_size += orig_bytes

    ratio = min(MAX_W / w, MAX_H / h, 1.0)
    new_w = int(round(w * ratio))
    new_h = int(round(h * ratio))
    if ratio < 1.0:
        img = img.resize((new_w, new_h), Image.LANCZOS)

    dest = source.with_suffix(".webp")

    if not dry_run:
        try:
            img.save(dest, "WEBP", quality=QUALITY, method=6)
        except Exception as e:
            print(f"  FAIL {source.name} : {e}")
            skipped += 1
            continue

        if source != dest and source.exists():
            source.unlink()

    new_bytes = dest.stat().st_size if not dry_run else int(orig_bytes * 0.15)
    new_size += new_bytes

    pct = (new_bytes / orig_bytes * 100) if orig_bytes else 0
    print(
        f"  {source.name:<32} {w:>4}x{h:<4} -> "
        f"{new_w:>4}x{new_h:<4}  "
        f"{orig_bytes / 1024:>7.1f} KB -> {new_bytes / 1024:>7.1f} KB "
        f"({pct:>4.1f}%)"
    )

print("-" * 78)
pct = (new_size / orig_size * 100) if orig_size else 0
print(f"Total avant : {orig_size / 1024 / 1024:>7.2f} MB")
print(f"Total apres : {new_size / 1024 / 1024:>7.2f} MB ({pct:.1f}%)")
print(f"Skipped     : {skipped}")
