from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.responses import JSONResponse

from app.api.readiness import readiness_payload
from app.api.router import router
from app.core.config import settings
from app.core.logger import logger
from app.repositories.query_log_repository import QueryLogRepository


@asynccontextmanager
async def lifespan(app: FastAPI):
    settings.validate_runtime()
    logger.info(
        "Starting {app_name} env={environment} port={port} retrieval_mock={mock} query_logs={logs}",
        app_name=settings.APP_NAME,
        environment=settings.resolved_environment(),
        port=settings.PORT,
        mock=settings.RETRIEVAL_CLIENT_MOCK,
        logs=settings.QUERY_LOGS_ENABLED,
    )
    if settings.QUERY_LOGS_ENABLED:
        await QueryLogRepository().ensure_indexes()
        logger.info("query_logs indexes ensured")
    yield


app = FastAPI(
    title=settings.APP_NAME,
    version=settings.SERVICE_VERSION,
    lifespan=lifespan,
)

app.include_router(router)


@app.get("/healthz")
async def root_healthz():
    return {"status": "ok"}


@app.get("/readyz")
async def root_readyz():
    body, status_code = await readiness_payload()
    return JSONResponse(status_code=status_code, content=body)
