"""健康检查命令: rmqadm health_check <subcommand>"""

import sys

from rmqadm.client import RabbitMQClient
from rmqadm.formatter import print_json
from rich.console import Console

console = Console()


class HealthCheckCommands:
    """运行 RabbitMQ 健康检查"""

    def __init__(self, client: RabbitMQClient):
        self._client = client

    def _check(self, path: str, description: str, format: str):
        """执行健康检查并输出结果"""
        resp = self._client.session.get(self._client._url(path))
        if format == "json":
            try:
                print_json(resp.json())
            except Exception:
                print(resp.text)
        else:
            if resp.ok:
                console.print(f"[green]OK[/green]  {description}")
            else:
                try:
                    body = resp.json()
                    reason = body.get("reason", resp.text)
                except Exception:
                    reason = resp.text
                console.print(f"[red]FAIL[/red] {description}: {reason}", err=True)
                sys.exit(1)

    def local_alarms(self, format: str = "table"):
        """检查目标节点是否有本地资源告警

        Args:
            format: 输出格式，table 或 json（默认 table）
        """
        self._check("/health/checks/local-alarms", "No local alarms", format)

    def cluster_wide_alarms(self, format: str = "table"):
        """检查集群范围内是否有资源告警

        Args:
            format: 输出格式，table 或 json（默认 table）
        """
        self._check("/health/checks/alarms", "No cluster-wide alarms", format)

    def node_is_quorum_critical(self, format: str = "table"):
        """检查目标节点下线是否会导致仲裁丢失

        Args:
            format: 输出格式，table 或 json（默认 table）
        """
        self._check(
            "/health/checks/node-is-quorum-critical",
            "Node is not quorum-critical",
            format,
        )

    def virtual_hosts(self, format: str = "table"):
        """检查所有 vhost 是否正常运行

        Args:
            format: 输出格式，table 或 json（默认 table）
        """
        self._check("/health/checks/virtual-hosts", "All virtual hosts running", format)

    def port_listener(self, port: int, format: str = "table"):
        """检查指定端口是否有监听器

        Args:
            port:   要检查的端口号
            format: 输出格式，table 或 json（默认 table）
        """
        self._check(
            f"/health/checks/port-listener/{port}",
            f"Port {port} has a listener",
            format,
        )

    def protocol_listener(self, protocol: str, format: str = "table"):
        """检查指定协议是否有监听器（如 amqp/amqps/mqtt/stomp）

        Args:
            protocol: 协议别名，如 amqp、amqps、mqtt、stomp
            format:   输出格式，table 或 json（默认 table）
        """
        self._check(
            f"/health/checks/protocol-listener/{protocol}",
            f"Protocol '{protocol}' has a listener",
            format,
        )
