# backend/serve.py — Launches FastAPI + Socket.IO API server (Milestone 6)
# Run with:  uvicorn serve:socket_app --host 0.0.0.0 --port 8000 --reload
#
# This module:
#  1. Initialises the database (creates tables if missing)
#  2. Exports `socket_app` — the combined FastAPI + Socket.IO ASGI app
#     that uvicorn (or any ASGI server) can run directly.
#
# The Telegram bot runner (run.py) remains a separate process.

import asyncio
from contextlib import asynccontextmanager

import database as db
from api import socket_app, app  # noqa: F401 — re-exported for uvicorn


@asynccontextmanager
async def lifespan(application):
    """FastAPI lifespan: initialise DB on startup."""
    await db.init_db()
    print("✅ negoT8 API server ready")
    yield
    print("👋 negoT8 API server shutting down")


# Attach the lifespan to the inner FastAPI app so uvicorn triggers it
app.router.lifespan_context = lifespan

# `socket_app` is the ASGI entry-point (Socket.IO wraps FastAPI).
# Uvicorn command:  uvicorn serve:socket_app --port 8000
