import asyncio
import logging
from collections.abc import Awaitable

from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse

from app.core import db

logger = logging.getLogger(__name__)

router = APIRouter()

CHECK_TIMEOUT_SECONDS = 3


async def _check(name: str, probe: Awaitable[None]) -> str:
    try:
        await asyncio.wait_for(probe, CHECK_TIMEOUT_SECONDS)
    except Exception:
        logger.exception("Health check failed: %s", name)
        return "down"
    return "ok"


# Infrastructure endpoint for monitoring: no user token, and it reveals only ok/down.
@router.get("/health")
async def health(request: Request) -> JSONResponse:
    database, livekit = await asyncio.gather(
        _check("database", db.ping(request.app.state.db_engine)),
        _check("livekit", request.app.state.livekit.ping()),
    )
    checks = {"database": database, "livekit": livekit}
    healthy = all(result == "ok" for result in checks.values())
    return JSONResponse(
        status_code=200 if healthy else 503,
        content={"status": "ok" if healthy else "degraded", "checks": checks},
    )
