"""绑定管理命令: rmqadm bindings <subcommand>"""

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


class BindingsCommands:
    """管理 RabbitMQ 绑定关系"""

    _LIST_COLUMNS = ["vhost", "source", "destination_type", "destination", "routing_key"]

    def __init__(self, client: RabbitMQClient, default_vhost: str = "/"):
        self._client = client
        self._default_vhost = default_vhost

    def list(self, vhost: str = None, format: str = "table"):
        """列出绑定关系

        Args:
            vhost:  指定 vhost，不填则列出所有 vhost 的绑定
            format: 输出格式，table 或 json（默认 table）
        """
        if vhost:
            path = f"/bindings/{self._client.encode_name(vhost)}"
        else:
            path = "/bindings"
        data = self._client.get(path)
        if format == "json":
            print_json(data)
        else:
            print_table(data, columns=self._LIST_COLUMNS)

    def create(self, source: str, destination: str, routing_key: str = "",
               destination_type: str = "queue", vhost: str = None):
        """创建绑定

        Args:
            source:           源交换机名称
            destination:      目标队列或交换机名称
            routing_key:      路由键（默认空）
            destination_type: 目标类型：queue 或 exchange（默认 queue）
            vhost:            vhost 名称（默认 /）
        """
        vhost = vhost or self._default_vhost
        enc_vhost = self._client.encode_name(vhost)
        enc_src = self._client.encode_name(source)
        enc_dst = self._client.encode_name(destination)
        # destination_type: q=queue, e=exchange
        dst_char = "q" if destination_type == "queue" else "e"
        path = f"/bindings/{enc_vhost}/e/{enc_src}/{dst_char}/{enc_dst}"
        body = {"routing_key": routing_key, "arguments": {}}
        self._client.post(path, body)
        print(f"Binding '{source}' -> '{destination}' (routing_key='{routing_key}') created.")

    def delete(self, source: str, destination: str, routing_key: str = "",
               destination_type: str = "queue", vhost: str = None):
        """删除绑定

        Args:
            source:           源交换机名称
            destination:      目标队列或交换机名称
            routing_key:      路由键
            destination_type: 目标类型：queue 或 exchange（默认 queue）
            vhost:            vhost 名称（默认 /）
        """
        vhost = vhost or self._default_vhost
        enc_vhost = self._client.encode_name(vhost)
        enc_src = self._client.encode_name(source)
        enc_dst = self._client.encode_name(destination)
        enc_rk = self._client.encode_name(routing_key) if routing_key else routing_key
        dst_char = "q" if destination_type == "queue" else "e"
        path = f"/bindings/{enc_vhost}/e/{enc_src}/{dst_char}/{enc_dst}/{enc_rk}"
        self._client.delete(path)
        print(f"Binding '{source}' -> '{destination}' (routing_key='{routing_key}') deleted.")
