from __future__ import annotations

import os
import re
from pathlib import Path
from typing import Any

import yaml

_PKG_ROOT = Path(__file__).resolve().parents[2]


def resolve_env_value(value: Any) -> Any:
    if isinstance(value, str) and value.startswith("${") and value.endswith("}"):
        return os.environ.get(value[2:-1]) or None
    if isinstance(value, dict):
        return {k: resolve_env_value(v) for k, v in value.items()}
    if isinstance(value, list):
        return [resolve_env_value(v) for v in value]
    return value


def load_mcp_config(path: Path | None = None) -> dict[str, Any]:
    cfg_path = path or _PKG_ROOT / "config" / "mcp.yaml"
    if not cfg_path.is_file():
        return {"servers": {}}
    with cfg_path.open(encoding="utf-8") as f:
        raw = yaml.safe_load(f) or {}
    return resolve_env_value(raw)


def list_enabled_servers(config: dict[str, Any] | None = None, *, runtime: str = "auto") -> dict[str, dict[str, Any]]:
    cfg = config or load_mcp_config()
    servers = cfg.get("servers") or {}
    out: dict[str, dict[str, Any]] = {}
    for name, spec in servers.items():
        if not isinstance(spec, dict) or not spec.get("enabled"):
            continue
        allowed = spec.get("runtime") or ["mac", "docker"]
        if runtime != "auto" and runtime not in allowed:
            continue
        out[name] = spec
    return out
