"""Application startup file selected in cPanel's Setup Python App."""

from __future__ import annotations

import os
import sys
import threading
from pathlib import Path


APP_DIR = Path(__file__).resolve().parent
if str(APP_DIR) not in sys.path:
    sys.path.insert(0, str(APP_DIR))
os.chdir(APP_DIR)

from a2wsgi import ASGIMiddleware  # noqa: E402
from main import app  # noqa: E402


# a2wsgi starts an asyncio thread when ASGIMiddleware is instantiated.
# Passenger may import the startup module in a preloader and fork afterwards;
# threads do not survive that fork, leaving every request waiting forever.
# Build the adapter lazily inside each worker and rebuild it if the PID changes.
_adapter = None
_adapter_pid = None
_adapter_lock = threading.Lock()


def _worker_adapter():
    global _adapter, _adapter_pid
    current_pid = os.getpid()
    if _adapter is None or _adapter_pid != current_pid:
        with _adapter_lock:
            if _adapter is None or _adapter_pid != current_pid:
                _adapter = ASGIMiddleware(app)
                _adapter_pid = current_pid
    return _adapter


# CloudLinux loads this module from its generated passenger_wsgi.py wrapper and
# expects a WSGI callable named "application".
def application(environ, start_response):
    return _worker_adapter()(environ, start_response)
