from __future__ import annotations

from ..ha_client import HAClient
from ..models import CheckResult, HAEventType, Severity
from .base import Check


class HeartbeatCheck(Check):
    """Pings HA /api/ to verify the REST API is reachable.

    Validates the end-to-end pipeline: shared HAClient → check → event emitter.
    """

    name = "heartbeat"

    def __init__(self, ha_client: HAClient) -> None:
        self._client = ha_client

    async def run(self) -> list[CheckResult]:
        try:
            data = await self._client.get_api_status()
            if isinstance(data, dict) and "message" in data:
                return []
            return [CheckResult(
                healthy=False,
                event_type=HAEventType.ha_websocket_dead,
                severity=Severity.error,
                message=f"HA API returned unexpected response: {data!r}",
                payload={"response": str(data)},
            )]
        except Exception as exc:
            return [CheckResult(
                healthy=False,
                event_type=HAEventType.ha_websocket_dead,
                severity=Severity.error,
                message=f"HA API unreachable: {exc}",
                payload={"error": str(exc)},
            )]
