import os
import sys

# 1. Setup paths
sys.path.insert(0, os.path.dirname(__file__))
_cached_app = None
# 2. Define a "Wrapper" function
# Passenger sees this function and thinks the app has started successfully.
def application(environ, start_response):
    global _cached_app
    try:
        from a2wsgi import ASGIMiddleware
        from app import app
        if _cached_app is None:
            # Initialize the bridge
            _cached_app = ASGIMiddleware(app)
        
        # Handle the actual request
        return _cached_app(environ, start_response)
    except Exception as e:
        # If it fails, this will actually print the error to the browser
        start_response('500 Internal Server Error', [('Content-Type', 'text/plain')])
        return [str(e).encode()]