import utils.openapi_patch  # noqa: F401

from contextlib import asynccontextmanager

from fastapi import Depends, FastAPI
from fastapi.security import OAuth2PasswordBearer

from ai_platform.router import router as ai_platform_router
from app.config import settings
from core.router import router as core_router
from core.websocket.router import router as websocket_router
from online_dev.router import router as online_dev_router
from utils.auth_middleware import AuthPermissionMiddleware
from utils.redis import RedisClient


oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="/api/v1/core/auth/login/oauth2",
    auto_error=False,
)


@asynccontextmanager
async def lifespan(app: FastAPI):
    from app.config_manager import config_manager

    await config_manager.warmup()
    try:
        yield
    finally:
        await RedisClient.close()


app = FastAPI(
    title=settings.APP_NAME,
    description="AI Agent Admin API",
    version="1.0.0",
    debug=settings.DEBUG,
    lifespan=lifespan,
    swagger_ui_init_oauth={
        "usePkceWithAuthorizationCodeGrant": True,
    },
)

app.add_middleware(AuthPermissionMiddleware)

app.include_router(core_router, prefix="/api/core", dependencies=[Depends(oauth2_scheme)])
app.include_router(ai_platform_router, prefix="/api/ai", dependencies=[Depends(oauth2_scheme)])
app.include_router(online_dev_router, prefix="/api/online_dev", dependencies=[Depends(oauth2_scheme)])
app.include_router(websocket_router)


@app.get("/", tags=["root"])
async def root():
    return {
        "message": f"Welcome to {settings.APP_NAME}",
        "env": settings.ENV,
        "docs": "/docs",
    }


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(
        "main:app",
        host=settings.APP_HOST,
        port=settings.APP_PORT,
        reload=settings.DEBUG,
    )
