import os
import uuid
import logging
from werkzeug.utils import secure_filename
from flask import current_app, url_for

logger = logging.getLogger(__name__)

# ---------------------------------------------------------------------------
# Magic Bytes — file type whitelist verified by actual binary header
# ---------------------------------------------------------------------------
MAGIC_SIGNATURES = {
    # Images
    b'\xff\xd8\xff':            'jpg',   # JPEG
    b'\x89PNG\r\n\x1a\n':      'png',   # PNG
    b'GIF87a':                  'gif',   # GIF87a
    b'GIF89a':                  'gif',   # GIF89a
    b'RIFF':                    'webp',  # WebP (RIFF container, further checked below)
    # Documents
    b'%PDF':                    'pdf',   # PDF
}

ALLOWED_EXTENSIONS = {'jpg', 'jpeg', 'png', 'gif', 'webp', 'pdf'}


class FileValidationError(ValueError):
    """Raised when a file fails validation (wrong type, disguised extension, etc.)."""
    pass


class StorageService:
    """
    Handles file uploads with security validation and optional image optimization.
    Supports: local storage (future: s3, gdrive).
    """

    # ------------------------------------------------------------------
    # Public API
    # ------------------------------------------------------------------

    @staticmethod
    def save(file, folder='uploads', *, validate=True, compress=False,
             max_size=None, quality=85, resize=None) -> str:
        """
        Saves a file to the configured storage with optional validation and compression.

        Args:
            file:       FileStorage object from Flask request.
            folder:     Subfolder inside the upload root.
            validate:   If True, check Magic Bytes against whitelist (default ON).
            compress:   If True, compress image via Pillow after saving.
            max_size:   Tuple (max_width, max_height) — resize to fit, keep aspect ratio.
            quality:    JPEG/WebP compression quality (1–100).
            resize:     Tuple (width, height) — exact resize (e.g. logo 256×256).

        Returns:
            Relative path/key to the stored file.

        Raises:
            FileValidationError: If the file fails magic bytes / extension check.
        """
        if not file or file.filename == '':
            return None

        driver = current_app.config.get('STORAGE_DRIVER', 'local')

        if driver == 'local':
            return StorageService._save_local(
                file, folder,
                validate=validate,
                compress=compress,
                max_size=max_size,
                quality=quality,
                resize=resize,
            )
        else:
            raise NotImplementedError(f"Storage driver '{driver}' not implemented.")

    @staticmethod
    def url(file_key) -> str:
        """Returns the public URL for a stored file key."""
        if not file_key:
            return None
        driver = current_app.config.get('STORAGE_DRIVER', 'local')
        if driver == 'local':
            return url_for('static', filename=f"uploads/{file_key}", _external=True)
        return file_key

    # ------------------------------------------------------------------
    # Validation
    # ------------------------------------------------------------------

    @staticmethod
    def _detect_file_type(file_stream) -> str | None:
        """
        Read the first bytes and match against known magic signatures.
        Returns the detected extension or None if unrecognized.
        """
        header = file_stream.read(16)
        file_stream.seek(0)  # rewind for later use

        if not header:
            return None

        for magic, ext in MAGIC_SIGNATURES.items():
            if header.startswith(magic):
                # WebP needs extra check: RIFF....WEBP
                if magic == b'RIFF' and header[8:12] != b'WEBP':
                    continue
                return ext

        return None

    @staticmethod
    def _validate_file(file) -> str:
        """
        Validates file by checking:
          1. Extension is in the whitelist.
          2. Magic bytes match the declared extension.

        Returns the validated (safe) extension.
        Raises FileValidationError on failure.
        """
        filename = secure_filename(file.filename)
        declared_ext = filename.rsplit('.', 1)[1].lower() if '.' in filename else ''

        if declared_ext not in ALLOWED_EXTENSIONS:
            raise FileValidationError(
                f"File type '.{declared_ext}' is not allowed. "
                f"Allowed: {', '.join(sorted(ALLOWED_EXTENSIONS))}"
            )

        detected = StorageService._detect_file_type(file.stream)

        if detected is None:
            raise FileValidationError(
                "Could not verify file type from contents. File may be corrupted or disguised."
            )

        # Normalize jpeg ↔ jpg
        norm = lambda e: 'jpg' if e in ('jpg', 'jpeg') else e
        if norm(detected) != norm(declared_ext):
            raise FileValidationError(
                f"File extension '.{declared_ext}' does not match actual content (detected: {detected}). "
                f"File may be disguised."
            )

        return declared_ext

    # ------------------------------------------------------------------
    # Image Processing (Pillow)
    # ------------------------------------------------------------------

    @staticmethod
    def _is_image_ext(ext: str) -> bool:
        return ext in ('jpg', 'jpeg', 'png', 'gif', 'webp')

    @staticmethod
    def _process_image(file_path: str, *, compress=False, max_size=None,
                       quality=85, resize=None):
        """
        Process an image file in-place:
        - resize:   Exact resize to (w, h), e.g. for logos.
        - max_size: Fit within (max_w, max_h) while keeping aspect ratio.
        - compress: Re-save with quality setting for JPEG/WebP.

        Converts PNG/WebP to JPEG for better compression when compress=True,
        unless the image has transparency (RGBA).
        """
        try:
            from PIL import Image

            img = Image.open(file_path)
            original_format = img.format
            changed = False

            # --- Exact resize (e.g. logos) ---
            if resize:
                img = img.resize(resize, Image.LANCZOS)
                changed = True

            # --- Fit within max dimensions ---
            if max_size:
                img.thumbnail(max_size, Image.LANCZOS)
                changed = True

            # --- Determine save format & handle transparency ---
            has_alpha = img.mode in ('RGBA', 'LA', 'PA')

            if compress or changed:
                if has_alpha:
                    # Keep PNG for transparent images
                    img.save(file_path, 'PNG', optimize=True)
                else:
                    # Convert to RGB for JPEG compression
                    if img.mode != 'RGB':
                        img = img.convert('RGB')

                    # Save as JPEG (rename file if needed)
                    base, ext = os.path.splitext(file_path)
                    if ext.lower() not in ('.jpg', '.jpeg'):
                        new_path = base + '.jpg'
                        img.save(new_path, 'JPEG', quality=quality, optimize=True)
                        # Remove original non-JPEG file
                        if os.path.exists(file_path) and file_path != new_path:
                            os.remove(file_path)
                        return new_path
                    else:
                        img.save(file_path, 'JPEG', quality=quality, optimize=True)

            return file_path

        except ImportError:
            logger.warning("Pillow not installed — skipping image processing")
            return file_path
        except Exception as e:
            logger.error(f"Image processing failed for {file_path}: {e}")
            return file_path

    # ------------------------------------------------------------------
    # Local Storage Driver
    # ------------------------------------------------------------------

    @staticmethod
    def _save_local(file, folder, *, validate=True, compress=False,
                    max_size=None, quality=85, resize=None) -> str:
        """Save file locally with optional validation and image processing."""

        # 1. Validate
        if validate:
            ext = StorageService._validate_file(file)
        else:
            filename = secure_filename(file.filename)
            ext = filename.rsplit('.', 1)[1].lower() if '.' in filename else 'bin'

        # 2. Generate unique filename
        new_filename = f"{uuid.uuid4()}.{ext}"

        # 3. Ensure directory exists
        base_path = current_app.config.get('UPLOAD_FOLDER', 'static/uploads')
        upload_path = os.path.join(base_path, folder)
        os.makedirs(upload_path, exist_ok=True)

        file_path = os.path.join(upload_path, new_filename)

        # 4. Save raw file
        file.save(file_path)

        # 5. Image processing (if applicable)
        needs_processing = compress or max_size or resize
        if needs_processing and StorageService._is_image_ext(ext):
            processed_path = StorageService._process_image(
                file_path,
                compress=compress,
                max_size=max_size,
                quality=quality,
                resize=resize,
            )
            # Update filename if format changed (e.g. png → jpg)
            if processed_path != file_path:
                new_filename = os.path.basename(processed_path)

        relative_key = f"{folder}/{new_filename}"
        logger.info(f"File saved: {relative_key}")
        return relative_key
