import asyncio

from fastapi import APIRouter, Request
from sqlalchemy import text

router = APIRouter(tags=["health"])


@router.get("/health")
async def health(request: Request) -> dict[str, object]:
    components: dict[str, dict[str, str]] = {
        "app": {"status": "ok"},
        "sqlite": {"status": "ok"},
        "milvus": {"status": "ok"},
    }

    try:
        async with request.app.state.database.engine.connect() as connection:
            await connection.execute(text("SELECT 1"))
    except Exception:
        components["sqlite"] = {"status": "error"}

    try:
        await asyncio.to_thread(request.app.state.vector_store.ping)
    except Exception:
        components["milvus"] = {"status": "error"}

    overall = "ok" if all(item["status"] == "ok" for item in components.values()) else "degraded"
    return {"status": overall, "components": components}
