"""Stream 管理命令: rmqadm streams <subcommand>

Stream 是 RabbitMQ 3.9+ 的持久化、可重复消费队列类型，
底层通过 /api/queues 接口以 x-queue-type=stream 参数操作。
"""

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


class StreamsCommands:
    """管理 RabbitMQ Streams（流式队列）"""

    _LIST_COLUMNS = ["name", "vhost", "durable", "state", "messages", "consumers"]

    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"):
        """列出 stream 队列

        Args:
            vhost:  指定 vhost，不填则列出所有 vhost 的 stream
            format: 输出格式，table 或 json（默认 table）
        """
        if vhost:
            path = f"/queues/{self._client.encode_name(vhost)}"
        else:
            path = "/queues"
        data = self._client.get(path)
        # 只保留 stream 类型
        streams = [q for q in data if q.get("type") == "stream"]
        if format == "json":
            print_json(streams)
        else:
            print_table(streams, columns=self._LIST_COLUMNS)

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

        Args:
            name:   stream 名称
            vhost:  vhost 名称（默认 /）
            format: 输出格式，table 或 json（默认 table）
        """
        vhost = vhost or self._default_vhost
        path = f"/queues/{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, vhost: str = None,
                max_length_bytes: int = None,
                max_age: str = None,
                stream_max_segment_size_bytes: int = None):
        """声明一个 stream

        Args:
            name:                           stream 名称
            vhost:                          vhost 名称（默认 /）
            max_length_bytes:               stream 最大字节数（超出则截断旧消息）
            max_age:                        消息最大保留时间，如 7D、1Y（Y/M/D/h/m/s）
            stream_max_segment_size_bytes:  每个 segment 文件最大字节数
        """
        vhost = vhost or self._default_vhost
        arguments = {"x-queue-type": "stream"}
        if max_length_bytes is not None:
            arguments["x-max-length-bytes"] = max_length_bytes
        if max_age is not None:
            arguments["x-max-age"] = max_age
        if stream_max_segment_size_bytes is not None:
            arguments["x-stream-max-segment-size-bytes"] = stream_max_segment_size_bytes

        body = {"durable": True, "arguments": arguments}
        path = f"/queues/{self._client.encode_name(vhost)}/{self._client.encode_name(name)}"
        self._client.put(path, body)
        print(f"Stream '{name}' in vhost '{vhost}' declared.")

    def delete(self, name: str, vhost: str = None):
        """删除 stream

        Args:
            name:  stream 名称
            vhost: vhost 名称（默认 /）
        """
        vhost = vhost or self._default_vhost
        path = f"/queues/{self._client.encode_name(vhost)}/{self._client.encode_name(name)}"
        self._client.delete(path)
        print(f"Stream '{name}' in vhost '{vhost}' deleted.")
