"""Passenger/WSGI entrypoint for cPanel deployments.

Passenger loads this file from the application root and serves the callable named
`application`. Migrations (and the first-install seed) run here, under a file lock,
before the app is imported — so a fresh upload only needs a Start in cPanel.

Works with both cPanel's "Setup Python App" (CloudLinux) and the vanilla
"Application Manager": startup file `passenger_wsgi.py`, entry point `application`.
"""
import fcntl
import logging
import os
import sys
import traceback
from pathlib import Path

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))

for _sub in ("tmp", "logs", "uploads"):
    (APP_ROOT / _sub).mkdir(exist_ok=True)

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)-7s %(name)s: %(message)s",
)
log = logging.getLogger("deploy")
_file_handler = logging.FileHandler(APP_ROOT / "logs" / "startup.log")
_file_handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)-7s %(name)s: %(message)s"))
log.addHandler(_file_handler)
log.propagate = False


def _bootstrap() -> None:
    from alembic import command
    from alembic.config import Config

    from app.core.config import settings

    lock_path = APP_ROOT / "tmp" / "migrate.lock"
    with lock_path.open("w") as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        try:
            if settings.RUN_MIGRATIONS:
                cfg = Config(str(APP_ROOT / "alembic.ini"))
                cfg.set_main_option("script_location", str(APP_ROOT / "alembic"))
                log.info("applying database migrations")
                command.upgrade(cfg, "head")
            if settings.RUN_SEED:
                log.info("seeding reference data and the bootstrap admin")
                from app.db.seed import main as seed_main

                seed_main()
        finally:
            fcntl.flock(lock, fcntl.LOCK_UN)


try:
    _bootstrap()
except Exception:
    log.error("startup bootstrap failed:\n%s", traceback.format_exc())
    raise

# alembic's logging config may disable existing loggers; keep our file log alive.
log.disabled = False

from a2wsgi import ASGIMiddleware  # noqa: E402

from app.main import app as fastapi_app  # noqa: E402

log.info("serving FastAPI via a2wsgi (WSGI)")
application = ASGIMiddleware(fastapi_app)
