"""Broker health checks for readiness probes."""

from __future__ import annotations

from confluent_kafka.admin import AdminClient

from neonlink.config import Config


class HealthChecker:
    """Provides broker health checks for readiness probes.

    Uses the confluent-kafka AdminClient to query cluster metadata.
    """

    def __init__(self, cfg: Config) -> None:
        conf = cfg.to_confluent_config()
        if cfg.client_id:
            conf["client.id"] = cfg.client_id + "-health"
        self._admin = AdminClient(conf)

    def check(self, timeout_sec: float = 5.0) -> None:
        """Verify broker connectivity by requesting cluster metadata.

        Raises:
            RuntimeError: if the cluster is unreachable or returns no brokers.
        """
        metadata = self._admin.list_topics(timeout=timeout_sec)
        if not metadata.brokers:
            raise RuntimeError("neonlink: health check failed: no brokers returned")

    def check_topic_exists(self, topic: str, timeout_sec: float = 5.0) -> None:
        """Verify that a specific topic exists in the cluster.

        Raises:
            RuntimeError: if the topic does not exist or the cluster is unreachable.
        """
        metadata = self._admin.list_topics(timeout=timeout_sec)
        if topic not in metadata.topics:
            raise RuntimeError(f"neonlink: topic {topic!r} does not exist")
