"""Read Claude/MCP config files to discover configured MCP servers."""

from __future__ import annotations

import json
from dataclasses import dataclass, field
from pathlib import Path


@dataclass
class ServerConfig:
    name: str
    command: str
    args: list[str] = field(default_factory=list)


def find_config_file() -> Path | None:
    """Find the first available MCP config file."""
    candidates = [
        Path.cwd() / ".mcp.json",
        Path.home() / ".claude" / "settings.json",
        Path.home() / ".claude.json",
    ]
    for path in candidates:
        if path.is_file():
            return path
    return None


def parse_config(path: Path) -> list[ServerConfig]:
    """Parse an MCP config file and return server configurations."""
    data = json.loads(path.read_text())

    # Handle .mcp.json format: {"mcpServers": {"name": {"command": ..., "args": [...]}}}
    servers_dict = data.get("mcpServers", {})

    # Handle Claude settings.json format which may nest under different keys
    if not servers_dict and "mcp_servers" in data:
        servers_dict = data["mcp_servers"]

    servers = []
    for name, cfg in servers_dict.items():
        if not isinstance(cfg, dict):
            continue
        command = cfg.get("command", "")
        args = cfg.get("args", [])
        if command:
            servers.append(ServerConfig(name=name, command=command, args=args))

    return servers


def load_config() -> tuple[Path, list[ServerConfig]]:
    """Find and parse the MCP config file. Raises FileNotFoundError if none found."""
    path = find_config_file()
    if path is None:
        raise FileNotFoundError(
            "No MCP config found. Looked for:\n"
            "  .mcp.json (current directory)\n"
            "  ~/.claude/settings.json\n"
            "  ~/.claude.json"
        )
    return path, parse_config(path)
