"""资源限制管理命令: rmqadm vhost_limits / rmqadm user_limits"""

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


class VhostLimitsCommands:
    """管理 Virtual Host 资源限制（max-connections / max-queues）"""

    _LIST_COLUMNS = ["vhost", "value"]

    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"):
        """列出 vhost 资源限制

        Args:
            vhost:  指定 vhost，不填则列出所有 vhost 的限制
            format: 输出格式，table 或 json（默认 table）
        """
        if vhost:
            path = f"/vhost-limits/{self._client.encode_name(vhost)}"
        else:
            path = "/vhost-limits"
        data = self._client.get(path)
        if format == "json":
            print_json(data)
        else:
            # API 返回形如 [{"vhost": "/", "value": {"max-connections": 100}}]
            # 展开 value 字段
            flat = []
            for item in data:
                vhost_name = item.get("vhost", "")
                for limit_name, limit_val in item.get("value", {}).items():
                    flat.append({"vhost": vhost_name, "name": limit_name, "value": limit_val})
            print_table(flat, columns=["vhost", "name", "value"])

    def set(self, name: str, value: int, vhost: str = None):
        """设置 vhost 资源限制

        Args:
            name:  限制名称：max-connections 或 max-queues
            value: 限制值（-1 表示不限制）
            vhost: vhost 名称（默认 /）
        """
        vhost = vhost or self._default_vhost
        body = {"value": value}
        path = f"/vhost-limits/{self._client.encode_name(vhost)}/{self._client.encode_name(name)}"
        self._client.put(path, body)
        print(f"VHost limit '{name}={value}' for vhost '{vhost}' set.")

    def delete(self, name: str, vhost: str = None):
        """删除 vhost 资源限制

        Args:
            name:  限制名称：max-connections 或 max-queues
            vhost: vhost 名称（默认 /）
        """
        vhost = vhost or self._default_vhost
        path = f"/vhost-limits/{self._client.encode_name(vhost)}/{self._client.encode_name(name)}"
        self._client.delete(path)
        print(f"VHost limit '{name}' for vhost '{vhost}' deleted.")


class UserLimitsCommands:
    """管理每用户资源限制（max-connections / max-channels）"""

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

    def list(self, username: str = None, format: str = "table"):
        """列出用户资源限制

        Args:
            username: 指定用户名，不填则列出所有用户的限制
            format:   输出格式，table 或 json（默认 table）
        """
        if username:
            path = f"/user-limits/{self._client.encode_name(username)}"
        else:
            path = "/user-limits"
        data = self._client.get(path)
        if format == "json":
            print_json(data)
        else:
            flat = []
            for item in data:
                user = item.get("user", "")
                for limit_name, limit_val in item.get("value", {}).items():
                    flat.append({"user": user, "name": limit_name, "value": limit_val})
            print_table(flat, columns=["user", "name", "value"])

    def set(self, username: str, name: str, value: int):
        """设置用户资源限制

        Args:
            username: 用户名
            name:     限制名称：max-connections 或 max-channels
            value:    限制值（-1 表示不限制）
        """
        body = {"value": value}
        path = f"/user-limits/{self._client.encode_name(username)}/{self._client.encode_name(name)}"
        self._client.put(path, body)
        print(f"User limit '{name}={value}' for user '{username}' set.")

    def delete(self, username: str, name: str):
        """删除用户资源限制

        Args:
            username: 用户名
            name:     限制名称：max-connections 或 max-channels
        """
        path = f"/user-limits/{self._client.encode_name(username)}/{self._client.encode_name(name)}"
        self._client.delete(path)
        print(f"User limit '{name}' for user '{username}' deleted.")
