from fastapi import FastAPI, Request
from fastapi.responses import RedirectResponse
from fastapi.staticfiles import StaticFiles
from contextlib import asynccontextmanager
from app.routers import router

import config
from utils import logger

from utils.background import init_scheduler, scheduler_lifespan

# Инициализация задач планировщика (без запуска)
init_scheduler()


async def initDB():
    from db import DATABASE_URL
    from db.initialize import DatabaseInitializer

    try:
        force = False
        reNewDB = False
        await DatabaseInitializer(DATABASE_URL).initialize(force, reNewDB)
        logger.info("База данных инициализирована")
    except Exception as e:
        logger.error(f"Инициализация базы завершилась ошибкой: {str(e)}", exc_info=True)


@asynccontextmanager
async def lifespan(app: FastAPI):
    # Запускаем lifespan планировщика
    async with scheduler_lifespan():
        yield


app = FastAPI(
    title="Medods to N3 Health API",
    description="API for medods-to-n3-health",
    version="0.1.0",
    lifespan=lifespan,
)


async def auth_middleware(request: Request, call_next):
    from db.schemas import Settings

    path = request.url.path

    if path.startswith(("/login", "/static", "/favicon.ico", "/api", "/test")):
        return await call_next(request)

    auth_token = request.cookies.get("auth_token")

    # 1️⃣ Нет токена
    if not auth_token:
        return RedirectResponse("/login", status_code=302)

    # 2️⃣ Проверка токена
    token_check = await Settings.verifyToken(auth_token)

    # 3️⃣ Невалидный токен → удалить cookie + редирект
    if not token_check.success:
        response = RedirectResponse("/login", status_code=302)
        response.delete_cookie("auth_token", path="/")
        return response

    # 4️⃣ Всё ок
    return await call_next(request)


app.mount(
    "/static", StaticFiles(directory=f"{config.RELOAD_DIR}/app/static"), name="static"
)

app.middleware("http")(auth_middleware)
app.include_router(router)


def startServer():
    import uvicorn

    logger.info("Starting server...")
    uvicorn.run(
        "init:app",
        host="0.0.0.0",
        port=80,
        reload=True,
        reload_dirs=[config.RELOAD_DIR],
    )


async def main():
    startServer()


if __name__ == "__main__":
    import asyncio

    asyncio.run(initDB())

    asyncio.run(main())
