from fastapi import HTTPException, Request
from loguru import logger

from session_hub_core.config import DatabaseConfig
from session_hub_core.query import QueryAPI


def build_query_api() -> QueryAPI | None:
    try:
        return QueryAPI(DatabaseConfig.from_env())
    except Exception as exc:
        logger.warning("database not configured, starting without DB access: {}", exc)
        return None


def get_query_api(request: Request) -> QueryAPI:
    query_api: QueryAPI | None = getattr(request.app.state, "query_api", None)
    if query_api is None:
        raise HTTPException(status_code=503, detail="database not configured")
    return query_api
