import sys
import os
import io

# Set the current directory in the path
sys.path.insert(0, os.path.dirname(__file__))

from app import app as asgi_app
from a2wsgi import ASGIMiddleware

_application = ASGIMiddleware(asgi_app)


def application(environ, start_response):
    """
    LiteSpeed WSGI bridge for FastAPI (ASGI) via a2wsgi.

    LiteSpeed's wsgi.input is a blocking synchronous stream. When a2wsgi tries
    to read it asynchronously inside its event loop thread, it deadlocks —
    causing the worker to hang until LiteSpeed kills it with SIGTERM (signal 15).

    Fix: pre-read the ENTIRE request body from LiteSpeed's stream into a BytesIO
    buffer BEFORE handing the environ to a2wsgi. This makes wsgi.input a clean,
    non-blocking in-memory stream that a2wsgi can read freely.
    """
    try:
        
        content_length = environ.get('CONTENT_LENGTH', '') or '0'
        length = int(content_length)
    except (ValueError, TypeError):
        length = 0

    # Pre-read body from LiteSpeed's blocking stream into memory
    if length > 0:
        body = environ['wsgi.input'].read(length)
    else:
        # For requests with no explicit Content-Length (e.g. GET, HEAD, DELETE),
        # supply an empty buffer so a2wsgi never blocks waiting for data.
        body = b''

    environ['wsgi.input'] = io.BytesIO(body)
    environ['CONTENT_LENGTH'] = str(len(body))

    return _application(environ, start_response)
