import os
import uuid
from PIL import Image
from werkzeug.utils import secure_filename
from flask import current_app

ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'svg', 'webp'}
MAX_FILE_SIZE = 2 * 1024 * 1024  # 2MB
MAX_IMAGE_SIZE = (400, 400)  # Resize to max 400x400


def allowed_file(filename):
    """Check if file has allowed extension."""
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


def validate_image_size(file):
    """Validate file size."""
    file.seek(0, os.SEEK_END)
    size = file.tell()
    file.seek(0)
    return size <= MAX_FILE_SIZE


def sanitize_svg(content):
    """Sanitize SVG content to remove potential scripts."""
    dangerous_tags = ['script', 'embed', 'iframe', 'object', 'link', 'style']
    dangerous_attrs = [
        'onload', 'onerror', 'onclick', 'onmouseover', 'onmouseout',
        'onfocus', 'onblur', 'javascript:', 'data:'
    ]

    for tag in dangerous_tags:
        content = content.replace(f'<{tag}', '').replace(f'</{tag}>')

    for attr in dangerous_attrs:
        content = content.replace(attr, '')

    return content


def resize_image(file, max_size=MAX_IMAGE_SIZE):
    """Resize image to fit within max_size while preserving aspect ratio."""
    try:
        img = Image.open(file)
        file_format = img.format

        # Only resize if image is larger than max_size
        if img.width > max_size[0] or img.height > max_size[1]:
            img.thumbnail(max_size, Image.Resampling.LANCZOS)

            # Create a new file-like object
            output = io.BytesIO()
            img.save(output, format=file_format, quality=85, optimize=True)
            output.seek(0)
            return output

        return file
    except Exception as e:
        current_app.logger.error(f"Image resize error: {e}")
        return file


import io


def upload_logo(file, upload_type='logos'):
    """
    Upload and process a logo image.

    Args:
        file: FileStorage object from Flask request
        upload_type: Subdirectory for uploads (logos, avatars, etc.)

    Returns:
        str: URL path to the uploaded file, or None if upload fails
    """
    if not file:
        return None

    if not allowed_file(file.filename):
        current_app.logger.warning(f"Invalid file extension: {file.filename}")
        return None

    if not validate_image_size(file):
        current_app.logger.warning(f"File too large: {file.filename}")
        return None

    # Handle SVG files separately (no resize)
    if file.filename.lower().endswith('.svg'):
        content = file.read().decode('utf-8')
        content = sanitize_svg(content)

        filename = secure_filename(file.filename)
        unique_name = f"{uuid.uuid4().hex}_{filename}"
        upload_path = os.path.join(current_app.config.get('UPLOAD_FOLDER', 'app/static/uploads'), upload_type, unique_name)

        os.makedirs(os.path.dirname(upload_path), exist_ok=True)

        with open(upload_path, 'w', encoding='utf-8') as f:
            f.write(content)

        return f"/static/uploads/{upload_type}/{unique_name}"

    # Handle raster images (resize and optimize)
    file.seek(0)

    # Always process the image properly
    try:
        img = Image.open(file)
        file_format = img.format or 'PNG'

        # Resize if larger than max_size
        if img.width > MAX_IMAGE_SIZE[0] or img.height > MAX_IMAGE_SIZE[1]:
            img.thumbnail(MAX_IMAGE_SIZE, Image.Resampling.LANCZOS)

        # Prepare filename
        filename = secure_filename(file.filename)
        # Ensure extension matches output format
        base_name = os.path.splitext(filename)[0]
        ext = file_format.lower()
        unique_name = f"{uuid.uuid4().hex}_{base_name}.{ext}"
        upload_path = os.path.join(current_app.config.get('UPLOAD_FOLDER', 'app/static/uploads'), upload_type, unique_name)

        os.makedirs(os.path.dirname(upload_path), exist_ok=True)

        # Save the image
        img.save(upload_path, format=file_format, quality=85, optimize=True)

        return f"/static/uploads/{upload_type}/{unique_name}"
    except Exception as e:
        current_app.logger.error(f"Image processing error: {e}")
        return None


def delete_file(url):
    """
    Delete a file from the uploads directory.

    Args:
        url: URL path to the file (e.g., /static/uploads/logos/file.png)

    Returns:
        bool: True if file was deleted, False otherwise
    """
    if not url or not url.startswith('/static/uploads/'):
        return False

    # Convert URL to file path
    file_path = os.path.join('app', url.lstrip('/'))

    try:
        if os.path.exists(file_path):
            os.remove(file_path)
            current_app.logger.info(f"Deleted file: {file_path}")
            return True
    except Exception as e:
        current_app.logger.error(f"Error deleting file {file_path}: {e}")

    return False
