"""Heartbeat API — pulse history, status, and deviations for the cardiogram UI."""

from __future__ import annotations

from fastapi import APIRouter, Request

router = APIRouter(prefix="/heartbeat", tags=["heartbeat"])


@router.get("/status")
async def heartbeat_status(request: Request) -> dict:
    """Get current heartbeat status (running, last pulse, totals)."""
    return await request.app.state.heartbeat.get_status()


@router.get("/history")
async def heartbeat_history(request: Request, hours: int = 24, limit: int = 200) -> list[dict]:
    """Get heartbeat pulse history for the cardiogram chart.

    Returns chronological list of pulses with timestamp, status, and task counts.
    Default: last 24 hours, up to 200 pulses.
    """
    return await request.app.state.heartbeat.get_history(hours=hours, limit=limit)


@router.get("/deviations")
async def heartbeat_deviations(request: Request, limit: int = 50) -> list[dict]:
    """Get recent deviations (non-normal pulses) with details."""
    return await request.app.state.heartbeat.get_deviations(limit=limit)


@router.post("/pulse")
async def trigger_pulse(request: Request) -> dict:
    """Manually trigger a heartbeat pulse."""
    observations = await request.app.state.heartbeat.run_once()
    return {"observations": observations, "count": len(observations)}
