"""Real WSGI callable. Imported by wsgi.py and passenger_wsgi.py.

cPanel often does imp.load_source('wsgi', 'wsgi.py'). Never
`from wsgi import application` in this chain.
"""
from __future__ import annotations

import os
import sys
import threading
import traceback
from pathlib import Path

os.environ.setdefault("PYTHONUNBUFFERED", "1")
try:
    sys.stderr.reconfigure(line_buffering=True, write_through=True)  # type: ignore[attr-defined]
    sys.stdout.reconfigure(line_buffering=True, write_through=True)  # type: ignore[attr-defined]
except Exception:
    pass

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

print(f"potd wsgi: loading pid={os.getpid()} file={__file__}", file=sys.stderr, flush=True)

from dotenv import load_dotenv  # noqa: E402

load_dotenv(APP_ROOT / ".env")

from a2wsgi import ASGIMiddleware  # noqa: E402
from backend.app.main import app as asgi_app  # noqa: E402

print(f"potd wsgi: imported FastAPI pid={os.getpid()}", file=sys.stderr, flush=True)


class _LazyASGI:
    def __init__(self) -> None:
        self._lock = threading.Lock()
        self._wsgi = None

    def __call__(self, environ, start_response):
        try:
            script = environ.get("SCRIPT_NAME") or ""
            if script == "/":
                environ["SCRIPT_NAME"] = ""
            path = environ.get("PATH_INFO") or ""
            if path != "/" and path.endswith("/"):
                environ["PATH_INFO"] = path.rstrip("/") or "/"
            if self._wsgi is None:
                with self._lock:
                    if self._wsgi is None:
                        print(
                            f"potd wsgi: first request pid={os.getpid()} "
                            f"path={environ.get('PATH_INFO', '')}",
                            file=sys.stderr,
                            flush=True,
                        )
                        self._wsgi = ASGIMiddleware(asgi_app)
            return self._wsgi(environ, start_response)
        except Exception:
            traceback.print_exc(file=sys.stderr)
            sys.stderr.flush()
            raise


application = _LazyASGI()
