import sys
import os
import traceback

sys.setrecursionlimit(5000)

app_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, app_dir)

os.makedirs(os.path.join(app_dir, "logs"), exist_ok=True)
os.makedirs(os.path.join(app_dir, "frontend", "assets"), exist_ok=True)

_application = None

def application(environ, start_response):
    global _application
    if _application is None:
        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(os.path.join(app_dir, "crash_log.txt"), "w") as f:
                    f.write(error_details)
            except:
                pass
            status = '200 OK'
            body = b"App Crashed:\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]
    return _application(environ, start_response)
