"""MCP provider config — auto-managed by the app, not user-editable.

Loaded from config/mcp-providers.yaml. UI (Vastian first-run wizard,
System > Integrations) writes to this file.
"""

from __future__ import annotations

import logging
from dataclasses import dataclass
from pathlib import Path

import yaml

logger = logging.getLogger(__name__)

# src/vastian/mcp/providers.py -> project root = parents[3]
_PROJECT_ROOT = Path(__file__).resolve().parents[3]
DEFAULT_PROVIDERS_PATH = _PROJECT_ROOT / "config" / "mcp-providers.yaml"


@dataclass
class MCPProviderConfig:
    """Config for a single MCP provider."""

    id: str
    url: str
    auth: str  # "github" | "bearer" | "none"
    enabled: bool
    api_key_env: str | None = None  # e.g. ZO_API_KEY for bearer auth


def load_mcp_providers(path: Path | None = None) -> dict[str, MCPProviderConfig]:
    """Load MCP provider config from YAML.

    Args:
        path: Path to mcp-providers.yaml. Defaults to config/mcp-providers.yaml.

    Returns:
        Dict mapping provider id -> MCPProviderConfig. Only enabled providers.
    """
    cfg_path = path or DEFAULT_PROVIDERS_PATH
    if not cfg_path.exists():
        return _default_providers_dict()

    try:
        data = yaml.safe_load(cfg_path.read_text(encoding="utf-8"))
    except Exception as e:
        logger.warning("Failed to load MCP providers from %s: %s", cfg_path, e)
        return _default_providers_dict()

    providers: dict[str, MCPProviderConfig] = {}
    raw = data.get("providers") or data
    for pid, pdata in (raw or {}).items():
        if isinstance(pdata, dict):
            cfg = MCPProviderConfig(
                id=pid,
                url=str(pdata.get("url", "")),
                auth=str(pdata.get("auth", "none")),
                enabled=bool(pdata.get("enabled", True)),
                api_key_env=pdata.get("api_key_env"),
            )
            if cfg.enabled and cfg.url:
                providers[pid] = cfg
    return providers if providers else _default_providers_dict()


def _default_providers_dict() -> dict[str, MCPProviderConfig]:
    """Sensible defaults when no config file exists."""
    return {
        "giga": MCPProviderConfig(
            id="giga",
            url="https://mcp.gigamind.dev/mcp",
            auth="github",
            enabled=True,
        ),
        "zo": MCPProviderConfig(
            id="zo",
            url="https://api.zo.computer/mcp",
            auth="bearer",
            enabled=True,
            api_key_env="ZO_API_KEY",
        ),
    }
