import os

from django.conf import settings
from django.shortcuts import get_object_or_404
from django.http import HttpResponse, FileResponse

from sorl.thumbnail import get_thumbnail

from .models import PostFileModel


THUMBNAIL_SIZES = {
    "sx": (64, ".thumb_64.jpg"),
    "sm": (256, ".thumb_256.jpg"),
    "md": (748, ".thumb_748.jpg"),
    "lg": (1024, ".thumb_1024.jpg"),
    "xl": (2048, ".thumb_2048.jpg"),
}


def get_thumbnail_file(source_path, size_key):
    """Generates and retrieves the thumbnail file."""
    size, suffix = THUMBNAIL_SIZES.get(size_key, (None, ""))
    if size:
        thumbnail_file = get_thumbnail(source_path, str(size), upscale=False)
        return os.path.abspath(
            os.path.join(settings.MEDIA_ROOT, thumbnail_file.name)
        ), suffix
    return None, ""


def serve_content_file(request, file_hash):
    """
    View function to serve content files for download or inline viewing.
    """

    download = request.GET.get("d") == "0"
    thumbnail_key = request.GET.get("t")

    try:
        obj_file = get_object_or_404(PostFileModel, hash_blake3=file_hash)
        file_name = obj_file.name.first().filename
        file_type = obj_file.file_type
        source_file = obj_file.file

        # Use thumbnail if requested and file type is image
        if thumbnail_key and file_type != "image":
            source_file = obj_file.thumbnail

        # Retrieve the requested thumbnail file if applicable
        if thumbnail_key in THUMBNAIL_SIZES:
            thumbnail_path, suffix = get_thumbnail_file(source_file.path, thumbnail_key)
            if thumbnail_path:
                file_name += suffix
                file = open(thumbnail_path, "rb")
            else:
                file = source_file.file
        else:
            file = source_file.file

        response = FileResponse(file)
        disposition_type = "attachment" if download else "inline"
        response["Content-Disposition"] = f'{disposition_type}; filename="{file_name}"'

        return response

    except Exception as e:
        print(f"Error serving file: {e}")
        return HttpResponse("File not found", status=404)