import hashlib
import os
import uuid

from flask import Blueprint, current_app, jsonify, request, send_from_directory, url_for
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.document import Document
from app.models.support_request import SupportRequest
from app.models.user import User
from app.models.volunteer_application import VolunteerApplication
from app.services.permissions import jwt_roles_required


documents_bp = Blueprint('documents', __name__, url_prefix='/api/v1/documents')
csrf.exempt(documents_bp)
MAX_DOCUMENT_SIZE = 5 * 1024 * 1024
ALLOWED_EXTENSIONS = {'pdf', 'jpg', 'jpeg', 'png', 'webp'}


def _file_signature_is_allowed(extension, content):
    signatures = {
        'pdf': content.startswith(b'%PDF-'),
        'jpg': content.startswith(b'\xff\xd8\xff'),
        'jpeg': content.startswith(b'\xff\xd8\xff'),
        'png': content.startswith(b'\x89PNG\r\n\x1a\n'),
        'webp': len(content) >= 12 and content[:4] == b'RIFF' and content[8:12] == b'WEBP',
    }
    return signatures.get(extension, False)


def store_private_document(uploaded_file, owner_type, owner_id):
    """Validate and privately store an attachment before its database record is added."""
    if uploaded_file is None or not uploaded_file.filename or owner_type not in {'volunteer', 'support'}:
        raise ValueError('A file and a valid owner type are required')
    safe_name = secure_filename(uploaded_file.filename)
    extension = safe_name.rsplit('.', 1)[-1].lower() if '.' in safe_name else ''
    if not safe_name or extension not in ALLOWED_EXTENSIONS:
        raise ValueError('File type is not allowed')

    content = uploaded_file.stream.read(MAX_DOCUMENT_SIZE + 1)
    if not content or len(content) > MAX_DOCUMENT_SIZE:
        raise ValueError('Files must be between 1 byte and 5 MB')
    if not _file_signature_is_allowed(extension, content):
        raise ValueError('File content does not match the permitted file type')

    storage_name = f'{uuid.uuid4().hex}.{extension}'
    private_directory = os.path.join(current_app.instance_path, 'private_uploads')
    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 document upload.')
        raise

    content_types = {
        'pdf': 'application/pdf',
        'jpg': 'image/jpeg',
        'jpeg': 'image/jpeg',
        'png': 'image/png',
        'webp': 'image/webp',
    }
    document = Document(
        owner_type=owner_type,
        owner_id=owner_id,
        stored_path=storage_name,
        original_name=safe_name[:255],
        mime_type=content_types[extension],
        size=len(content),
        checksum=hashlib.sha256(content).hexdigest(),
        access_class='private',
    )
    return document, destination


def _can_access_owner(owner):
    user = db.session.get(User, int(get_jwt_identity()))
    if user.role.role_name == 'Admin':
        return True
    return getattr(owner, 'assigned_to', None) == user.id


@documents_bp.route('/upload', methods=['POST'])
@jwt_roles_required('Admin', 'Verifier')
def upload_document():
    uploaded_file = request.files.get('file')
    owner_type = request.form.get('owner_type', '').strip()
    owner_id = request.form.get('owner_id', '').strip()
    if uploaded_file is None or not uploaded_file.filename or owner_type not in {'volunteer', 'support'}:
        return jsonify({'error': 'A file and a valid owner type are required'}), 400
    try:
        owner_id = int(owner_id)
    except (TypeError, ValueError):
        return jsonify({'error': 'A valid owner ID is required'}), 400

    owner = (
        VolunteerApplication.query.get(owner_id) if owner_type == 'volunteer'
        else SupportRequest.query.get(owner_id)
    )
    if owner is None:
        return jsonify({'error': 'Application not found'}), 404
    if not _can_access_owner(owner):
        return jsonify({'error': 'Application not found'}), 404

    try:
        document, destination = store_private_document(uploaded_file, owner_type, owner_id)
    except ValueError as exc:
        return jsonify({'error': str(exc)}), 400
    except OSError:
        current_app.logger.exception('Could not store private document.')
        return jsonify({'error': 'The document could not be stored'}), 500
    db.session.add(document)
    try:
        db.session.commit()
    except SQLAlchemyError:
        db.session.rollback()
        try:
            os.remove(destination)
        except OSError:
            current_app.logger.exception('Could not remove uncommitted private document.')
        current_app.logger.exception('Could not save private document metadata.')
        return jsonify({'error': 'The document could not be saved'}), 500

    return jsonify({
        'message': 'Document uploaded',
        'document_id': document.id,
        'file_name': document.original_name,
    }), 201


@documents_bp.route('/owner', methods=['GET'])
@jwt_roles_required('Admin', 'Verifier')
def list_owner_documents():
    owner_type = request.args.get('owner_type', '').strip()
    try:
        owner_id = int(request.args.get('owner_id', ''))
    except (TypeError, ValueError):
        return jsonify({'error': 'A valid owner ID is required'}), 400
    if owner_type not in {'volunteer', 'support'}:
        return jsonify({'error': 'A valid owner type is required'}), 400

    owner_model = VolunteerApplication if owner_type == 'volunteer' else SupportRequest
    owner = db.session.get(owner_model, owner_id)
    if owner is None or not _can_access_owner(owner):
        return jsonify({'error': 'Application not found'}), 404
    documents = Document.query.filter_by(
        owner_type=owner_type,
        owner_id=owner_id,
        access_class='private',
    ).order_by(Document.uploaded_at.desc()).limit(50).all()
    return jsonify({
        'documents': [{
            'id': item.id,
            'file_name': item.original_name,
            'size': item.size,
            'mime_type': item.mime_type,
            'uploaded_at': item.uploaded_at.isoformat() if item.uploaded_at else None,
            'download_url': url_for('documents.download_document', document_id=item.id),
        } for item in documents],
        'total': len(documents),
    }), 200


@documents_bp.route('/<int:document_id>', methods=['GET'])
@jwt_roles_required('Admin', 'Verifier')
def download_document(document_id):
    document = Document.query.filter_by(id=document_id, access_class='private').first()
    if document is None:
        return jsonify({'error': 'Document not found'}), 404
    if document.owner_type not in {'volunteer', 'support'}:
        return jsonify({'error': 'Document not found'}), 404
    owner_model = VolunteerApplication if document.owner_type == 'volunteer' else SupportRequest
    owner = db.session.get(owner_model, document.owner_id)
    if owner is None or not _can_access_owner(owner):
        return jsonify({'error': 'Document not found'}), 404
    return send_from_directory(
        os.path.join(current_app.instance_path, 'private_uploads'),
        document.stored_path,
        as_attachment=True,
        download_name=document.original_name,
        mimetype=document.mime_type,
    )
