from contextlib import asynccontextmanager

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

from domains.auth.api import router as auth_router
from domains.users.api import router as users_router
from domains.admin.api import router as admin_router
from domains.groups.api import router as groups_router
from domains.realtime.ws import router as realtime_router
from domains.notifications.api import router as notifications_router

from db.redis import redis_client
from fastapi_swagger import patch_fastapi


@asynccontextmanager
async def lifespan(app: FastAPI):

    # ---------- Startup ----------
    try:
        await redis_client.ping() # type: ignore
        print("Redis connected")

    except Exception as e:
        print("Redis connection failed:", e)

    yield

    # ---------- Shutdown ----------
    await redis_client.close()


app = FastAPI(
    title="NEDA API",
    description="Realtime Voice Communication Backend",
    version="1.0.0",
    lifespan=lifespan,
    docs_url=None,
    swagger_ui_oauth2_redirect_url=None
)
patch_fastapi(app,docs_url="/swagger")

# -------------------------
# CORS
# -------------------------

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# -------------------------
# Routers
# -------------------------

app.include_router(auth_router)
app.include_router(users_router)
app.include_router(admin_router)
app.include_router(groups_router)
app.include_router(realtime_router)
app.include_router(notifications_router)