import os
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from PIL import Image
from io import BytesIO


def validate_image_file(file):
    """Validate image file"""
    allowed_extensions = ['.jpg', '.jpeg', '.png', '.webp']
    file_extension = os.path.splitext(file.name)[1].lower()
    
    if file_extension not in allowed_extensions:
        raise ValueError(f'Invalid file type. Allowed types: {", ".join(allowed_extensions)}')
    
    # Check file size (max 10MB)
    if file.size > 10 * 1024 * 1024:
        raise ValueError('File size exceeds 10MB limit')
    
    return True


def optimize_image(image_file, max_width=1920, max_height=1080, quality=85):
    """Optimize image file"""
    try:
        img = Image.open(image_file)
        
        # Convert to RGB if necessary
        if img.mode in ('RGBA', 'LA', 'P'):
            background = Image.new('RGB', img.size, (255, 255, 255))
            if img.mode == 'P':
                img = img.convert('RGBA')
            background.paste(img, mask=img.split()[-1] if img.mode in ('RGBA', 'LA') else None)
            img = background
        
        # Resize if necessary
        if img.width > max_width or img.height > max_height:
            img.thumbnail((max_width, max_height), Image.Resampling.LANCZOS)
        
        # Save optimized image
        output = BytesIO()
        img.save(output, format='JPEG', quality=quality, optimize=True)
        output.seek(0)
        
        return ContentFile(output.read(), name=image_file.name)
    except Exception as e:
        raise ValueError(f'Error optimizing image: {str(e)}')


def save_image(file, path, optimize=True):
    """Save image file with optional optimization"""
    validate_image_file(file)
    
    if optimize:
        file = optimize_image(file)
    
    return default_storage.save(path, file)

