"""cPanel / Passenger WSGI entry point for the LeadPilot API.

Passenger speaks WSGI, FastAPI speaks ASGI, so the ASGI app is wrapped with
``a2wsgi.ASGIMiddleware`` and exposed as the module-level name ``application``,
which is what the cPanel "Application startup file / Entry point" pair expects.

This file must sit in the application root, next to ``app/`` and
``requirements.txt``.

Three things differ from running under uvicorn locally, and each is handled here:

1. **Import path** - Passenger imports this module directly, so the application
   root is put on ``sys.path`` explicitly rather than relied upon.
2. **Working directory** - Passenger does not guarantee the process CWD, and both
   ``.env`` loading and the default relative SQLite path resolve against it. The
   CWD is pinned to the application root so behaviour matches local runs.
3. **Startup hook** - WSGI has no lifespan protocol, so FastAPI's ``lifespan``
   (which calls ``init_db()``) never fires under Passenger. The schema is created
   here instead. ``init_db()`` is idempotent, so the local uvicorn path that still
   runs the lifespan is unaffected.

Nothing about the application's architecture, routing or business logic changes.
"""

from __future__ import annotations

import logging
import os
import sys
from pathlib import Path

#: The application root - the directory holding this file, ``app/`` and ``requirements.txt``.
BASE_DIR = Path(__file__).resolve().parent

if str(BASE_DIR) not in sys.path:
    sys.path.insert(0, str(BASE_DIR))

# Pin the CWD so `.env` is found and any relative path resolves predictably.
try:
    os.chdir(BASE_DIR)
except OSError:  # pragma: no cover - only on an unusual hosting sandbox
    pass

# Keep the SQLite file in a dedicated data/ directory inside the application root
# rather than wherever Passenger happened to start the process. data/ ships with a
# deny-all .htaccess, because on cPanel a subdomain's document root can overlap the
# application root, which would otherwise make the database downloadable over HTTP.
# An explicitly configured LEADPILOT_DATABASE_URL always wins.
DATA_DIR = BASE_DIR / "data"
try:
    DATA_DIR.mkdir(mode=0o750, exist_ok=True)
except OSError:  # pragma: no cover - fall back to the application root
    DATA_DIR = BASE_DIR

os.environ.setdefault(
    "LEADPILOT_DATABASE_URL",
    f"sqlite:///{(DATA_DIR / 'leadpilot.db').as_posix()}",
)

from a2wsgi import ASGIMiddleware  # noqa: E402  (path setup must happen first)

from app.database import init_db  # noqa: E402
from app.main import app as asgi_app  # noqa: E402

logger = logging.getLogger("leadpilot.passenger")

# WSGI never triggers the ASGI lifespan, so the tables are created here.
init_db()
logger.info("LeadPilot schema ready at %s", os.environ["LEADPILOT_DATABASE_URL"])

#: The name cPanel's "Entry point" field must be set to.
application = ASGIMiddleware(asgi_app)
