"""连接管理命令: rmqadm connections <subcommand>"""

from rmqadm.client import RabbitMQClient
from rmqadm.formatter import print_table, print_json


class ConnectionsCommands:
    """查看和管理 RabbitMQ 连接"""

    _LIST_COLUMNS = ["name", "vhost", "user", "protocol", "state", "peer_host", "peer_port", "channels"]

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

    def list(self, format: str = "table"):
        """列出所有连接

        Args:
            format: 输出格式，table 或 json（默认 table）
        """
        data = self._client.get("/connections")
        if format == "json":
            print_json(data)
        else:
            print_table(data, columns=self._LIST_COLUMNS)

    def show(self, name: str, format: str = "table"):
        """显示连接详情

        Args:
            name:   连接名称
            format: 输出格式，table 或 json（默认 table）
        """
        data = self._client.get(f"/connections/{self._client.encode_name(name)}")
        if format == "json":
            print_json(data)
        else:
            print_table([data], columns=self._LIST_COLUMNS)

    def close(self, name: str, reason: str = "Closed via rmqadm"):
        """关闭指定连接

        Args:
            name:   连接名称
            reason: 关闭原因（默认 'Closed via rmqadm'）
        """
        # 通过发送 DELETE 请求关闭连接
        import sys

        # 使用 X-Reason 请求头传递原因
        path = f"/connections/{self._client.encode_name(name)}"
        resp = self._client.session.delete(
            self._client._url(path),
            headers={"X-Reason": reason},
        )
        if not resp.ok and resp.status_code != 404:
            print(f"Error: {resp.status_code} - {resp.text}", file=sys.stderr)
            sys.exit(1)
        print(f"Connection '{name}' closed.")
