import os
import sys
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager

from fastapi import FastAPI
from loguru import logger

from session_hub_api.dependencies import build_query_api
from session_hub_api.routes import embeddings as embeddings_routes
from session_hub_api.routes import search as search_routes
from session_hub_api.routes import sessions as sessions_routes
from session_hub_api.routes import system as system_routes


def create_app() -> FastAPI:
    @asynccontextmanager
    async def lifespan(app: FastAPI) -> AsyncIterator[None]:
        app.state.query_api = build_query_api()
        yield
        query_api = getattr(app.state, "query_api", None)
        if query_api is not None:
            await query_api.close()

    logger.remove()
    logger.add(sys.stderr, level=os.environ.get("SESSION_HUB_LOG_LEVEL", "INFO"))

    app = FastAPI(title="Session Hub", version="0.1.0", lifespan=lifespan)
    app.include_router(sessions_routes.router)
    app.include_router(search_routes.router)
    app.include_router(embeddings_routes.router)
    app.include_router(system_routes.router)
    return app


app = create_app()
