"""Liveness and readiness (lesson 21)."""
import asyncio

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

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


@router.get("/livez", include_in_schema=False)
async def livez() -> dict:
    return {"status": "ok"}                    # the process and its event loop answer: nothing more


@router.get("/readyz", include_in_schema=False)
async def readyz(request: Request) -> JSONResponse:
    if request.state.health.draining:
        return JSONResponse({"status": "draining"}, status_code=503)
    try:
        async with request.state.sessions() as session:
            await asyncio.wait_for(session.execute(text("SELECT 1")), timeout=1.0)
    except Exception as exc:                   # timeout, refused connection, bad credentials...
        return JSONResponse({"status": "unready", "database": type(exc).__name__}, status_code=503)
    return JSONResponse({"status": "ready", "database": "ok"})
