import sys
import os
import traceback

sys.path.insert(0, os.path.dirname(__file__))

try:
    from a2wsgi import ASGIMiddleware
    from app.main import app
    application = ASGIMiddleware(app)
except Exception as e:
    error_details = traceback.format_exc()
    try:
        with open("crash_log.txt", "w") as f:
            f.write(error_details)
    except:
        pass
        
    def application(environ, start_response):
        status = '200 OK'  # Force 200 OK so cPanel doesn't drop the error text
        body = b"App Crashed on Startup:\n\n" + error_details.encode('utf-8')
        headers = [
            ('Content-Type', 'text/plain; charset=utf-8'),
            ('Content-Length', str(len(body)))
        ]
        start_response(status, headers)
        return [body]
