import io
import sys


class ChunkedMiddleware:
    def __init__(self, get_response):
        development = any(arg for arg in sys.argv if "manage.py" in arg)
        support = any(s in arg for arg in sys.argv for s in ("uvicorn", "hypercorn", "daphne"))

        if not support and not development:
            raise Exception('Chunked request not supported. Use a server that handles Transfer-Encoding.')

        self.get_response = get_response

    def __call__(self, request):
        has_transfer_encoding = 'Transfer-Encoding' in request.headers
        transfer_encoding = request.headers.get('Transfer-Encoding')

        if has_transfer_encoding and transfer_encoding == 'chunked':
            content_length = request.META.get('CONTENT_LENGTH')
            if content_length in (None, '0'):
                request.META['CONTENT_LENGTH'] = str(len(request.body))
                request._stream = io.BytesIO(request.body)

        response = self.get_response(request)
        return response
