"""Operator 策略管理命令: rmqadm operator_policies <subcommand>"""

import json as _json

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


class OperatorPoliciesCommands:
    """管理 RabbitMQ Operator 策略（只能由 operator 设置，用户策略无法覆盖）"""

    _LIST_COLUMNS = ["vhost", "name", "pattern", "apply-to", "priority", "definition"]

    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"):
        """列出 operator 策略

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

    def show(self, name: str, vhost: str = None, format: str = "table"):
        """显示 operator 策略详情

        Args:
            name:   策略名称
            vhost:  vhost 名称（默认 /）
            format: 输出格式，table 或 json（默认 table）
        """
        vhost = vhost or self._default_vhost
        path = f"/operator-policies/{self._client.encode_name(vhost)}/{self._client.encode_name(name)}"
        data = self._client.get(path)
        if format == "json":
            print_json(data)
        else:
            print_table([data], columns=self._LIST_COLUMNS)

    def declare(self, name: str, pattern: str, definition: str,
                apply_to: str = "queues", priority: int = 0, vhost: str = None):
        """创建或更新 operator 策略

        Args:
            name:       策略名称
            pattern:    匹配实体名称的正则表达式
            definition: 策略定义（JSON 字符串），如 '{"max-length":1000}'
            apply_to:   应用对象：queues/classic_queues/quorum_queues/streams（默认 queues）
            priority:   优先级（默认 0）
            vhost:      vhost 名称（默认 /）
        """
        vhost = vhost or self._default_vhost
        try:
            definition_dict = _json.loads(definition)
        except _json.JSONDecodeError as e:
            raise ValueError(f"definition 必须是合法的 JSON 字符串: {e}") from e

        body = {
            "pattern": pattern,
            "definition": definition_dict,
            "apply-to": apply_to,
            "priority": priority,
        }
        path = f"/operator-policies/{self._client.encode_name(vhost)}/{self._client.encode_name(name)}"
        self._client.put(path, body)
        print(f"Operator policy '{name}' in vhost '{vhost}' declared.")

    def delete(self, name: str, vhost: str = None):
        """删除 operator 策略

        Args:
            name:  策略名称
            vhost: vhost 名称（默认 /）
        """
        vhost = vhost or self._default_vhost
        path = f"/operator-policies/{self._client.encode_name(vhost)}/{self._client.encode_name(name)}"
        self._client.delete(path)
        print(f"Operator policy '{name}' in vhost '{vhost}' deleted.")
