"""
Entry point for cPanel's "Setup Python App" (Phusion Passenger).

Passenger expects a WSGI callable named `application` in this file.
FastAPI is ASGI-based, so we wrap it with a2wsgi's ASGIMiddleware to
bridge the two — everything else in the app (routing, background
training threads, prediction endpoint, file uploads) works unmodified.

cPanel setup:
  - Application startup file : passenger_wsgi.py
  - Application Entry point  : application
  - Make sure `a2wsgi` is in requirements.txt and installed via
    cPanel's "Run Pip Install" (or `pip install -r requirements.txt`
    inside the app's virtualenv over SSH).

Unlike Render, Passenger does NOT use a $PORT env var — it manages the
process and routes HTTP through Apache/LiteSpeed itself, so run.py is
not used in this deployment path.
"""

import sys
import os

# Make sure the project root is importable regardless of Passenger's cwd.
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, BASE_DIR)

from a2wsgi import ASGIMiddleware  # noqa: E402
from app.main import app as fastapi_app  # noqa: E402
from app.database import init_db, SessionLocal  # noqa: E402
from app.services import model_service  # noqa: E402

# IMPORTANT: Passenger/WSGI has no "lifespan" protocol, so FastAPI's
# @app.on_event("startup") hook in app/main.py (which creates DB tables
# and auto-deploys any committed model) never fires under this deployment
# path. Run the same startup logic explicitly, once, at import time —
# Passenger imports this module exactly once per worker process.
init_db()
_db = SessionLocal()
try:
    model_service.sync_committed_models(_db)
finally:
    _db.close()

application = ASGIMiddleware(fastapi_app)
