from collections.abc import AsyncIterator
from contextlib import asynccontextmanager

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

from .config import SETTINGS
from .kafka.producer import get_producer
from .rest import rest_router
from .ws import ws_router


@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
    producer = get_producer()
    await producer.start()
    try:
        yield
    finally:
        await producer.stop()


app = FastAPI(title="Matyan Frontier", lifespan=lifespan)

app.add_middleware(
    CORSMiddleware,  # ty:ignore[invalid-argument-type]
    allow_origins=SETTINGS.cors_origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(ws_router, prefix="/api/v1")
app.include_router(rest_router, prefix="/api/v1")
