"""消费者查看命令: rmqadm consumers <subcommand>"""

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


class ConsumersCommands:
    """查看 RabbitMQ 消费者"""

    _LIST_COLUMNS = ["queue.name", "channel_details.name", "consumer_tag",
                     "ack_required", "prefetch_count", "exclusive"]

    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"/consumers/{self._client.encode_name(vhost)}"
        else:
            path = "/consumers"
        data = self._client.get(path)
        if format == "json":
            print_json(data)
        else:
            # 展开嵌套字段以便表格显示
            flat = []
            for item in data:
                row = {}
                for col in self._LIST_COLUMNS:
                    if "." in col:
                        parts = col.split(".")
                        val = item
                        for p in parts:
                            val = val.get(p, "") if isinstance(val, dict) else ""
                        row[col] = val
                    else:
                        row[col] = item.get(col, "")
                flat.append(row)
            print_table(flat, columns=self._LIST_COLUMNS)
