"""
Utilities shared across blueprints.
"""
import os
import secrets
from PIL import Image


def save_image(file):
    """Save uploaded image file and return the path."""
    if file and file.filename:
        # Generate a random filename to avoid conflicts
        random_hex = secrets.token_hex(8)
        _, f_ext = os.path.splitext(file.filename)
        filename = random_hex + f_ext
        
        # Create filepath for saving
        filepath = os.path.join('static', 'images', filename)
        
        # Resize image FIRST before saving to disk
        try:
            img = Image.open(file.stream)  # Open from uploaded file stream
            # Resize to 500x500 pixels max, maintaining aspect ratio
            img.thumbnail((500, 500), Image.Resampling.LANCZOS)
            # Save the resized image directly (don't save original first)
            img.save(filepath, optimize=True, quality=85)
        except Exception as e:
            # If resizing fails, save original file as-is
            file.seek(0)  # Reset file stream position
            file.save(filepath)
        
        # Return the path for database storage
        return f'images/{filename}'
    return None