"""配置文件加载：从 JSON 文件中读取 RabbitMQ 集群连接信息"""

import json
import re
import sys
from pathlib import Path

# 默认配置文件路径
DEFAULT_CONFIG_PATH = Path.home() / ".config" / "rabbitmq" / "admin.json"


def _strip_trailing_commas(text: str) -> str:
    """移除 JSON 中对象/数组末尾的多余逗号（常见手写 JSON 错误）"""
    # 匹配 , 后面紧跟 } 或 ] 之间只有空白/注释的情况
    return re.sub(r",(\s*[}\]])", r"\1", text)


def load_config(config_path: Path = None) -> list[dict]:
    """从 JSON 文件加载集群配置列表

    Args:
        config_path: 配置文件路径，默认 ~/.config/rabbitmq/admin.json

    Returns:
        集群配置字典列表，每项含 name/description/host/port/username/password/vhost/scheme
    """
    path = config_path or DEFAULT_CONFIG_PATH
    path = Path(path).expanduser()

    if not path.exists():
        return []

    try:
        raw = path.read_text(encoding="utf-8")
        # 容错：移除对象/数组末尾的多余逗号
        cleaned = _strip_trailing_commas(raw)
        clusters = json.loads(cleaned)
    except json.JSONDecodeError as e:
        from rich.console import Console
        Console(stderr=True).print(
            f"[red]Error: 配置文件 {path} 解析失败: {e}[/red]"
        )
        sys.exit(1)

    if not isinstance(clusters, list):
        from rich.console import Console
        Console(stderr=True).print(
            f"[red]Error: 配置文件 {path} 格式错误，顶层应为 JSON 数组[/red]"
        )
        sys.exit(1)

    return clusters


def get_cluster(clusters: list[dict], name: str) -> dict:
    """按 name 字段从配置列表中查找集群

    Args:
        clusters: load_config() 返回的配置列表
        name:     集群别名（对应配置中的 name 字段）

    Returns:
        匹配的集群配置字典

    Raises:
        SystemExit: 找不到时打印可用集群并退出
    """
    for cluster in clusters:
        if cluster.get("name") == name:
            return cluster

    from rich.console import Console
    console = Console(stderr=True)
    console.print(f"[red]Error: 未找到集群 '{name}'，可用集群:[/red]")
    _print_clusters(clusters, console)
    sys.exit(1)


def _print_clusters(clusters: list[dict], console=None):
    """打印集群列表到 console（或新建一个）"""
    from rich.console import Console
    from rich.table import Table

    con = console or Console()
    table = Table(show_header=True, header_style="bold cyan")
    table.add_column("name")
    table.add_column("description")
    table.add_column("host")
    table.add_column("port")
    table.add_column("scheme")
    table.add_column("vhost")

    for c in clusters:
        table.add_row(
            c.get("name", ""),
            c.get("description", ""),
            c.get("host", "localhost"),
            str(c.get("port", 15672)),
            c.get("scheme", "http"),
            c.get("vhost", "/"),
        )
    con.print(table)
