#  Copyright (C) 2024
#  ABM, Moscow
#
#  UNPUBLISHED PROPRIETARY MATERIAL.
#  ALL RIGHTS RESERVED.
#
#  Authors: Vasya Svintsov <v.svintsov@techokert.ru>

from typing import Final, Awaitable

import aiohttp
from aiohttp import hdrs, web
from aiohttp.web_response import ContentCoding


ANY_COMPRESSION_ALGORITHM: Final[str] = '*'


@web.middleware
async def compress_middleware(
        request: web.Request, handler: aiohttp.typedefs.Handler, *args, **kwargs
) -> web.StreamResponse | Awaitable[web.StreamResponse]:

    preferred_compression_algorithm = None
    for header_value in request.headers.getall(hdrs.ACCEPT_ENCODING):
        preferred_compression_algorithm = next((alg for alg in ContentCoding if alg.value in header_value), None)
        if preferred_compression_algorithm:
            break

        if ANY_COMPRESSION_ALGORITHM in header_value:
            preferred_compression_algorithm = ContentCoding.deflate
            break

    response = await handler(request)
    if preferred_compression_algorithm:
        response.enable_compression(preferred_compression_algorithm)
    return response
