"""cPanel Phusion Passenger WSGI entrypoint for AegisTrade AI.

cPanel's 'Setup Python App' uses Phusion Passenger, which speaks WSGI.
This file adapts our async FastAPI ASGI application into WSGI.
"""
from __future__ import annotations

import os
import sys

# Ensure project root is on Python sys.path
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
if CURRENT_DIR not in sys.path:
    sys.path.insert(0, CURRENT_DIR)

try:
    # Use a2wsgi if installed to bridge ASGI (FastAPI) to WSGI (Passenger)
    from a2wsgi import ASGIMiddleware
    from backend.app.main import app

    application = ASGIMiddleware(app)
except ImportError:
    # Fallback wrapper if a2wsgi is not yet installed in virtualenv
    try:
        from asgiref.wsgi import WsgiToAsgi
        from backend.app.main import app
        # If someone passed WSGI to ASGI
        import asyncio
        from a2wsgi import ASGIMiddleware
        application = ASGIMiddleware(app)
    except Exception:
        def application(environ, start_response):
            status = '500 Internal Server Error'
            output = (
                b'AegisTrade AI: a2wsgi dependency missing in cPanel virtual environment.\n'
                b'Run: pip install a2wsgi in your cPanel Python terminal.\n'
            )
            response_headers = [('Content-type', 'text/plain; charset=utf-8'),
                                ('Content-Length', str(len(output)))]
            start_response(status, response_headers)
            return [output]
