import os
import shutil
import uuid

from flask import Blueprint, current_app, jsonify, request, send_from_directory
from flask_jwt_extended import get_jwt_identity
from sqlalchemy.exc import SQLAlchemyError
from werkzeug.utils import secure_filename

from app.extensions import csrf, db
from app.models.audit_log import AuditLog
from app.models.media_asset import MediaAsset
from app.services.permissions import jwt_roles_required


media_bp = Blueprint('media', __name__, url_prefix='/api/v1/media')
csrf.exempt(media_bp)
MAX_MEDIA_SIZE = 5 * 1024 * 1024
IMAGE_SIGNATURES = {
    'jpg': lambda content: content.startswith(b'\xff\xd8\xff'),
    'jpeg': lambda content: content.startswith(b'\xff\xd8\xff'),
    'png': lambda content: content.startswith(b'\x89PNG\r\n\x1a\n'),
    'webp': lambda content: len(content) >= 12 and content[:4] == b'RIFF' and content[8:12] == b'WEBP',
}


@media_bp.route('/', methods=['POST'])
@jwt_roles_required('Admin')
def add_media():
    uploaded_file = request.files.get('file')
    title = request.form.get('title', '').strip()
    alt_text = request.form.get('alt_text', '').strip()
    caption = request.form.get('caption', '').strip()
    pillar = request.form.get('pillar', '').strip()
    consent_confirmed = request.form.get('consent_confirmed') == 'true'
    try:
        media, destination = create_media_draft(
            uploaded_file,
            title,
            alt_text,
            caption,
            pillar,
            consent_confirmed,
            int(get_jwt_identity()),
        )
    except ValueError as exc:
        return jsonify({'error': str(exc)}), 400
    except OSError:
        current_app.logger.exception('Could not store uploaded media file.')
        return jsonify({'error': 'The media file could not be stored'}), 500
    db.session.add(media)
    try:
        db.session.flush()
        record_media_audit(media, int(get_jwt_identity()), 'media_uploaded')
        db.session.commit()
    except SQLAlchemyError:
        db.session.rollback()
        try:
            os.remove(destination)
        except OSError:
            current_app.logger.exception('Could not remove uncommitted media upload.')
        current_app.logger.exception('Could not save uploaded media metadata.')
        return jsonify({'error': 'The media item could not be saved'}), 500
    return jsonify({'message': 'Media uploaded as a draft', 'media_id': media.id}), 201


def create_media_draft(uploaded_file, title, alt_text, caption, pillar, consent_confirmed, uploader_id):
    """Validate an image and store it privately before creating a draft record."""
    if uploaded_file is None or not uploaded_file.filename or not title or not alt_text:
        raise ValueError('An image, title, and alt text are required')
    if len(title) > 150 or len(alt_text) > 255 or len(caption) > 5000 or len(pillar) > 100:
        raise ValueError('One or more fields exceed the allowed length')

    safe_name = secure_filename(uploaded_file.filename)
    extension = safe_name.rsplit('.', 1)[-1].lower() if '.' in safe_name else ''
    signature_check = IMAGE_SIGNATURES.get(extension)
    if signature_check is None:
        raise ValueError('Only JPEG, PNG, and WebP images are accepted')
    content = uploaded_file.stream.read(MAX_MEDIA_SIZE + 1)
    if not content or len(content) > MAX_MEDIA_SIZE:
        raise ValueError('Images must be between 1 byte and 5 MB')
    if not signature_check(content):
        raise ValueError('File content does not match the permitted image type')

    storage_name = f'{uuid.uuid4().hex}.{extension}'
    private_directory = os.path.join(current_app.instance_path, 'private_media')
    os.makedirs(private_directory, mode=0o700, exist_ok=True)
    destination = os.path.join(private_directory, storage_name)
    try:
        with open(destination, 'wb') as private_file:
            private_file.write(content)
    except OSError:
        try:
            if os.path.exists(destination):
                os.remove(destination)
        except OSError:
            current_app.logger.exception('Could not remove incomplete private media upload.')
        raise

    media = MediaAsset(
        title=title,
        media_type='image',
        storage_key=storage_name,
        caption=caption,
        alt_text=alt_text,
        pillar=pillar or None,
        consent_confirmed=consent_confirmed,
        status='draft',
        uploader=uploader_id,
    )
    return media, destination


def publish_media_asset(media, actor_id):
    """Publish a consented draft image and keep its private original."""
    if not media.consent_confirmed or not media.alt_text:
        return False, 'Confirmed consent and descriptive alt text are required', 400

    private_name = os.path.basename(media.storage_key)
    if not private_name or private_name != media.storage_key and not media.storage_key.startswith('images/approved/'):
        return False, 'Private media path is invalid', 404
    private_directory = os.path.join(current_app.instance_path, 'private_media')
    source = os.path.join(private_directory, private_name)
    if not os.path.isfile(source):
        return False, 'Private media file is missing or invalid', 404
    public_directory = os.path.join(current_app.static_folder, 'images', 'approved')
    try:
        os.makedirs(public_directory, exist_ok=True)
    except OSError:
        current_app.logger.exception('Could not create public media storage.')
        return False, 'The media item could not be published', 500
    destination = os.path.join(public_directory, private_name)
    already_public = os.path.exists(destination)
    try:
        shutil.copyfile(source, destination)
    except OSError:
        current_app.logger.exception('Could not copy media to public storage.')
        return False, 'The media item could not be published', 500

    media.storage_key = f'images/approved/{private_name}'
    media.status = 'active'
    record_media_audit(media, actor_id, 'media_published')
    try:
        db.session.commit()
    except SQLAlchemyError:
        db.session.rollback()
        if not already_public and os.path.exists(destination):
            try:
                os.remove(destination)
            except OSError:
                current_app.logger.exception('Could not remove uncommitted public media.')
        current_app.logger.exception('Could not publish media item.')
        return False, 'The media item could not be published', 500
    return True, '', 200


def record_media_audit(media, actor_id, action):
    db.session.add(AuditLog(
        actor=str(actor_id),
        action=action,
        entity="media_asset",
        safe_metadata=f"id={media.id}; status={media.status}",
    ))


@media_bp.route('/<int:media_id>/preview', methods=['GET'])
@jwt_roles_required('Admin')
def preview_media(media_id):
    media = db.session.get(MediaAsset, media_id)
    if media is None:
        return jsonify({'error': 'Media item not found'}), 404
    if media.status == 'active' and media.storage_key.startswith('images/approved/'):
        directory = current_app.static_folder
        filename = media.storage_key
    else:
        if os.path.basename(media.storage_key) != media.storage_key:
            return jsonify({'error': 'Private media path is invalid'}), 404
        directory = os.path.join(current_app.instance_path, 'private_media')
        filename = media.storage_key
    extension = filename.rsplit('.', 1)[-1].lower()
    media_type = 'jpeg' if extension in {'jpg', 'jpeg'} else extension
    return send_from_directory(directory, filename, as_attachment=False, mimetype=f'image/{media_type}')


@media_bp.route('/<int:media_id>/publish', methods=['POST'])
@jwt_roles_required('Admin')
def publish_media(media_id):
    media = db.session.get(MediaAsset, media_id)
    if media is None:
        return jsonify({'error': 'Media item not found'}), 404
    published, error, status_code = publish_media_asset(media, int(get_jwt_identity()))
    if not published:
        return jsonify({'error': error}), status_code
    return jsonify({'message': 'Media item published', 'media_id': media.id}), 200
