"""
Connection management helper functions.
"""
from __future__ import annotations

from ..config import load_config


def do_list_connections() -> dict:
    """
    列出所有已配置的 ES 连接。

    Returns:
        连接列表（敏感信息仅显示环境变量名，不显示实际值）
    """
    config = load_config()

    connections = []
    for p in config.profiles:
        connections.append({
            "profile": p.name,
            "env": p.env,
            "description": p.description or "无",
            "has_auth": p.has_auth(),
            "skip_product_check": p.skip_product_check,
            "env_vars": {
                k: v for k, v in {
                    "hosts": p.env_vars.hosts,
                    "username": p.env_vars.username,
                    "password": p.env_vars.password,
                }.items() if v is not None
            },
        })

    default_profile = config.default_profile()

    return {
        "connections": connections,
        "count": len(connections),
        "default": default_profile.name if default_profile else None,
    }


def do_get_connection(profile: str = "") -> dict:
    """
    获取指定连接的详细信息。
    """
    config = load_config()

    if profile:
        conn = config.get_profile(profile)
    else:
        conn = config.default_profile()

    if not conn:
        return {
            "found": False,
            "message": f"未找到 profile: {profile}" if profile else "无默认连接",
        }

    return {
        "found": True,
        "profile": conn.name,
        "env": conn.env,
        "description": conn.description or "无",
        "has_auth": conn.has_auth(),
        "skip_product_check": conn.skip_product_check,
        "env_vars": {
            k: v for k, v in {
                "hosts": conn.env_vars.hosts,
                "username": conn.env_vars.username,
                "password": conn.env_vars.password,
            }.items() if v is not None
        },
    }
