# -*- coding: utf-8 -*-
"""Read, write, and merge .mcp.json configuration files."""
import json
import copy
import os
import re
from pathlib import Path
from typing import Any, Dict, Optional


def read_config(path: str | Path) -> Dict[str, Any]:
    """Read and parse an .mcp.json file."""
    p = Path(path)
    if not p.exists():
        raise FileNotFoundError(f"Config not found: {p}")
    text = p.read_text(encoding="utf-8")
    return json.loads(text)


def write_config(path: str | Path, config: Dict[str, Any]) -> None:
    """Write config dict to an .mcp.json file."""
    p = Path(path)
    p.parent.mkdir(parents=True, exist_ok=True)
    p.write_text(json.dumps(config, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")


def merge_configs(base: Dict[str, Any], overlay: Dict[str, Any]) -> Dict[str, Any]:
    """Merge two configs. Overlay wins on conflicts.

    Server-level merge: overlay servers replace base servers with same name,
    new servers are added, base-only servers are preserved.
    """
    result = copy.deepcopy(base)
    base_servers = result.get("mcpServers", {})
    overlay_servers = overlay.get("mcpServers", {})

    for name, server_config in overlay_servers.items():
        base_servers[name] = copy.deepcopy(server_config)

    result["mcpServers"] = base_servers
    return result


def resolve_env_vars(config: Dict[str, Any]) -> Dict[str, Any]:
    """Replace ${VAR} references with actual environment variable values."""
    result = copy.deepcopy(config)
    pattern = re.compile(r"\$\{([^}]+)\}")

    def _resolve(value: Any) -> Any:
        if isinstance(value, str):
            def replacer(m):
                var_name = m.group(1)
                return os.environ.get(var_name, m.group(0))
            return pattern.sub(replacer, value)
        if isinstance(value, dict):
            return {k: _resolve(v) for k, v in value.items()}
        if isinstance(value, list):
            return [_resolve(item) for item in value]
        return value

    return _resolve(result)


def create_template() -> Dict[str, Any]:
    """Create a minimal .mcp.json template."""
    return {
        "mcpServers": {
            "example-server": {
                "command": "npx",
                "args": ["-y", "@example/mcp-server"],
                "env": {}
            }
        }
    }


def list_servers(config: Dict[str, Any]) -> list[Dict[str, str]]:
    """List all servers in a config with their transport type."""
    servers = []
    for name, cfg in config.get("mcpServers", {}).items():
        transport = "stdio"
        if "url" in cfg:
            transport = "http"
        elif cfg.get("type"):
            transport = cfg["type"]
        servers.append({
            "name": name,
            "command": cfg.get("command", cfg.get("url", "?")),
            "transport": transport,
        })
    return servers
