import asyncio
import logging
from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from backend.app.api.router import api_router
from backend.app.core.config import settings

logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    # Start Telegram bot polling in background
    bot_task = None
    if settings.TELEGRAM_BOT_TOKEN:
        from backend.app.bot import create_bot
        bot, dp = create_bot()
        bot_task = asyncio.create_task(dp.start_polling(bot))
        logger.info("Telegram bot polling started")

    yield

    # Shutdown
    if bot_task:
        bot_task.cancel()
        try:
            await bot_task
        except asyncio.CancelledError:
            pass
        logger.info("Telegram bot polling stopped")


app = FastAPI(
    title="VeloBrain",
    description="AI-Powered Cycling Training Platform",
    version="0.1.0",
    lifespan=lifespan,
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:5173"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(api_router)


@app.get("/health")
async def health():
    return {"status": "ok"}
