import os
import sys
import traceback

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

if BASE_DIR not in sys.path:
    sys.path.insert(0, BASE_DIR)


def error_application(environ, start_response):
    error_text = environ.get("APP_STARTUP_ERROR", "Erro desconhecido ao iniciar aplicação.")

    body = f"""
    <html>
      <head>
        <meta charset="utf-8">
        <title>Erro ao iniciar aplicação</title>
        <style>
          body {{
            font-family: Arial, sans-serif;
            padding: 32px;
            background: #f8fafc;
            color: #111827;
          }}

          pre {{
            white-space: pre-wrap;
            background: #111827;
            color: #f8fafc;
            padding: 20px;
            border-radius: 12px;
            overflow-x: auto;
          }}
        </style>
      </head>

      <body>
        <h1>Erro ao iniciar aplicação Python</h1>
        <p>O Passenger conseguiu carregar o arquivo <strong>passenger_wsgi.py</strong>, mas a aplicação FastAPI falhou ao iniciar.</p>
        <pre>{error_text}</pre>
      </body>
    </html>
    """.encode("utf-8")

    start_response(
        "500 Internal Server Error",
        [
            ("Content-Type", "text/html; charset=utf-8"),
            ("Content-Length", str(len(body))),
        ],
    )

    return [body]


try:
    from a2wsgi import ASGIMiddleware
    from webapp import app as fastapi_app

    application = ASGIMiddleware(fastapi_app)

except Exception:
    startup_error = traceback.format_exc()

    def application(environ, start_response):
        environ["APP_STARTUP_ERROR"] = startup_error
        return error_application(environ, start_response)