"""``GET /api/health`` — liveness + readiness probe.

SP19 expanded the shallow ``{"status": "ok", "version": ...}`` probe
into a snapshot of every subsystem:

* **db** — can we open a session and run ``SELECT 1``?
* **scheduler** — is the MFT polling loop running? same for the
  backup scheduler.
* **pubsub** — current subscriber counts per event kind.
* **batch** — most recent batch id + timestamp.

Returns ``status="ok"`` only when every subsystem is healthy.
``status="degraded"`` if any subsystem is unhappy but the API
itself is responsive. Per-subsystem errors are surfaced in the
respective dict so an operator doesn't have to guess.
"""
from __future__ import annotations

from fastapi import APIRouter, Request

from cyclone import __version__
from cyclone.security import get_health_snapshot


router = APIRouter()


@router.get("/api/health")
def health(request: Request) -> dict:
    snap = get_health_snapshot()
    # Fill in live pubsub subscriber counts using the per-request app
    # state (the snapshot builder doesn't have request context).
    bus = getattr(request.app.state, "event_bus", None)
    if bus is not None and hasattr(bus, "stats"):
        snap.pubsub = bus.stats()
    elif bus is not None:
        snap.pubsub = {"note": "EventBus.stats() not available"}
    else:
        snap.pubsub = {"note": "EventBus not attached (running outside lifespan?)"}
    return snap.to_dict()
