"""定义导入/导出命令: rmqadm definitions <subcommand>"""

import json
import sys

from rmqadm.client import RabbitMQClient
from rmqadm.formatter import print_json
from rich.console import Console

console = Console()


class DefinitionsCommands:
    """导入/导出 RabbitMQ 集群定义（vhosts/queues/exchanges/bindings/users 等）"""

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

    def export(self, file: str = None, vhost: str = None):
        """导出集群定义到文件或标准输出

        Args:
            file:  输出文件路径，不填则打印到标准输出
            vhost: 仅导出指定 vhost 的定义（不填则导出全集群）
        """
        if vhost:
            path = f"/definitions/{self._client.encode_name(vhost)}"
        else:
            path = "/definitions"

        data = self._client.get(path)
        content = json.dumps(data, indent=2, ensure_ascii=False)

        if file:
            with open(file, "w", encoding="utf-8") as f:
                f.write(content)
            console.print(f"[green]Definitions exported to '{file}'.[/green]")
        else:
            print_json(data)

    def import_file(self, file: str = None, vhost: str = None):
        """从文件导入定义

        Args:
            file:  定义 JSON 文件路径，不填则从标准输入读取
            vhost: 导入到指定 vhost（不填则导入全集群）
        """
        if file:
            with open(file, "r", encoding="utf-8") as f:
                content = f.read()
        else:
            console.print("[yellow]Reading definitions from stdin (Ctrl+D to end)...[/yellow]")
            content = sys.stdin.read()

        try:
            data = json.loads(content)
        except json.JSONDecodeError as e:
            console.print(f"[red]Error: 无效的 JSON 文件: {e}[/red]", err=True)
            sys.exit(1)

        if vhost:
            path = f"/definitions/{self._client.encode_name(vhost)}"
        else:
            path = "/definitions"

        self._client.post(path, data)
        console.print("[green]Definitions imported successfully.[/green]")
