from __future__ import annotations

from contextlib import asynccontextmanager
from typing import AsyncGenerator

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

from app.config import settings
from app.db import close_pool, init_pool
from app.middleware.logging import LoggingMiddleware
from app.services.ws_hub import hub as ws_hub  # noqa: F401


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
    await init_pool()
    yield
    await close_pool()


app = FastAPI(title="Sentinel Lens", lifespan=lifespan)

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

# Router registration
from app.routers import stats  # noqa: E402
from app.routers import logs  # noqa: E402
from app.routers import scrape  # noqa: E402
from app.routers import public  # noqa: E402
from app.routers import ws  # noqa: E402
app.include_router(stats.router, prefix="/api")
app.include_router(logs.router, prefix="/api")
app.include_router(scrape.router, prefix="/api")
app.include_router(public.router, prefix="/api/public")
app.include_router(ws.router)


@app.get("/")
async def health_check() -> dict:
    return {"status": "ok", "service": "sentinel-lens"}
