import sys
import os
sys.path.insert(0, os.path.dirname(__file__))
from app import app
import asyncio

def application(environ, start_response):
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    headers = []
    for key, value in environ.items():
        if key.startswith("HTTP_"):
            header_name = key[5:].lower().replace("_", "-")
            headers.append((header_name.encode(), value.encode()))
    if "CONTENT_TYPE" in environ:
        headers.append((b"content-type", environ["CONTENT_TYPE"].encode()))
    if "CONTENT_LENGTH" in environ and environ["CONTENT_LENGTH"]:
        headers.append((b"content-length", environ["CONTENT_LENGTH"].encode()))
    scope = {
        "type": "http",
        "asgi": {"version": "3.0"},
        "http_version": "1.1",
        "method": environ["REQUEST_METHOD"],
        "path": environ.get("PATH_INFO", "/"),
        "query_string": environ.get("QUERY_STRING", "").encode(),
        "root_path": environ.get("SCRIPT_NAME", ""),
        "scheme": environ.get("wsgi.url_scheme", "http"),
        "server": (environ.get("SERVER_NAME"), int(environ.get("SERVER_PORT", 80))),
        "headers": headers,
    }
    status_code = 200
    resp_headers = []
    body = b""

    async def receive():
        try:
            content_length = int(environ.get("CONTENT_LENGTH") or 0)
        except ValueError:
            content_length = 0
        if content_length > 0:
            raw_body = environ["wsgi.input"].read(content_length)
        else:
            raw_body = b""
        return {"type": "http.request", "body": raw_body, "more_body": False}

    async def send(message):
        nonlocal status_code, resp_headers, body
        if message["type"] == "http.response.start":
            status_code = message["status"]
            resp_headers = message.get("headers", [])
        elif message["type"] == "http.response.body":
            body += message.get("body", b"")

    loop.run_until_complete(app(scope, receive, send))
    status_map = {
        200: "200 OK",
        201: "201 Created",
        400: "400 Bad Request",
        401: "401 Unauthorized",
        403: "403 Forbidden",
        404: "404 Not Found",
        409: "409 Conflict",
        422: "422 Unprocessable Entity",
        500: "500 Internal Server Error",
    }
    start_response(
        status_map.get(status_code, f"{status_code} Unknown"),
        [(k.decode(), v.decode()) for k, v in resp_headers]
    )
    return [body]