"""Feature Flag 管理命令: rmqadm feature_flags <subcommand>"""

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

console = Console()


class FeatureFlagsCommands:
    """管理 RabbitMQ Feature Flags"""

    _LIST_COLUMNS = ["name", "state", "stability", "desc"]

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

    def list(self, format: str = "table"):
        """列出所有 feature flags 及其状态

        Args:
            format: 输出格式，table 或 json（默认 table）
        """
        data = self._client.get("/feature-flags")
        if format == "json":
            print_json(data)
        else:
            print_table(data, columns=self._LIST_COLUMNS)

    def enable(self, name: str):
        """启用指定 feature flag

        Args:
            name: feature flag 名称
        """
        self._client.put(f"/feature-flags/{self._client.encode_name(name)}/enable")
        console.print(f"[green]Feature flag '{name}' enabled.[/green]")

    def enable_all(self):
        """启用所有稳定版（stable）feature flags"""
        data = self._client.get("/feature-flags")
        enabled = 0
        for flag in data:
            if flag.get("state") != "enabled" and flag.get("stability") == "stable":
                self._client.put(
                    f"/feature-flags/{self._client.encode_name(flag['name'])}/enable"
                )
                console.print(f"[green]Enabled:[/green] {flag['name']}")
                enabled += 1
        if enabled == 0:
            console.print("[yellow]All stable feature flags are already enabled.[/yellow]")
        else:
            console.print(f"[green]{enabled} feature flag(s) enabled.[/green]")
