#!/usr/bin/env python3
"""
Script pour régénérer toutes les miniatures avec le nouveau ratio (48px)
"""
import os
import sys
from pathlib import Path

# Add app to path
sys.path.insert(0, str(Path(__file__).parent))

from app.db.session import get_peripherals_db
from app.models.peripheral import PeripheralPhoto
from app.utils.image_processor import ImageProcessor


def regenerate_thumbnails():
    """Régénérer toutes les miniatures"""
    db = next(get_peripherals_db())

    try:
        # Get all photos
        photos = db.query(PeripheralPhoto).all()

        total = len(photos)
        success = 0
        errors = 0

        print(f"📊 Trouvé {total} photos")
        print("=" * 60)

        for i, photo in enumerate(photos, 1):
            print(f"\n[{i}/{total}] Photo ID {photo.id} - {photo.filename}")

            # Check if main image exists
            if not os.path.exists(photo.stored_path):
                print(f"  ⚠️  Image principale introuvable : {photo.stored_path}")
                errors += 1
                continue

            # Get upload directory
            upload_dir = os.path.dirname(photo.stored_path)

            try:
                # Delete old thumbnail
                if photo.thumbnail_path and os.path.exists(photo.thumbnail_path):
                    old_size = os.path.getsize(photo.thumbnail_path)
                    os.remove(photo.thumbnail_path)
                    print(f"  🗑️  Ancienne miniature supprimée ({old_size} octets)")

                # Generate new thumbnail with aspect ratio preserved
                thumbnail_path, thumbnail_size = ImageProcessor.create_thumbnail_with_level(
                    image_path=photo.stored_path,
                    output_dir=upload_dir,
                    compression_level="medium"
                )

                # Update database
                photo.thumbnail_path = thumbnail_path
                db.commit()

                print(f"  ✅ Nouvelle miniature : {os.path.basename(thumbnail_path)} ({thumbnail_size} octets)")

                # Show dimensions
                from PIL import Image
                with Image.open(thumbnail_path) as img:
                    print(f"  📐 Dimensions : {img.width}×{img.height}px")

                success += 1

            except Exception as e:
                print(f"  ❌ Erreur : {e}")
                db.rollback()
                errors += 1

        print("\n" + "=" * 60)
        print(f"✅ Succès : {success}/{total}")
        print(f"❌ Erreurs : {errors}/{total}")

    finally:
        db.close()


if __name__ == "__main__":
    print("🖼️  Régénération des miniatures avec ratio d'aspect conservé (48px)")
    print("=" * 60)
    regenerate_thumbnails()
