import os

import pytest

from mcpbridge.config import BridgeConfig
from mcpbridge.exceptions import APIKeyMissingError, ConfigValidationError


def test_model_alias_resolution_openai():
    cfg = BridgeConfig.from_dict(
        {
            "llm": {"provider": "openai", "model": "gpt4o-mini", "api_key": "k"},
            "mcp": {"url": "http://localhost:3000", "transport": "streamable_http"},
            "prompt": {"system": "hi"},
        }
    )
    assert cfg.llm.model == "gpt-4o-mini"


def test_env_api_key_fallback(monkeypatch):
    monkeypatch.setenv("OPENAI_API_KEY", "envkey")
    cfg = BridgeConfig.from_dict(
        {
            "llm": {"provider": "openai", "model": "gpt4o"},
            "mcp": {"url": "http://localhost:3000", "transport": "streamable_http"},
            "prompt": {"system": "hi"},
        }
    )
    assert cfg.llm.api_key == "envkey"


def test_missing_api_key_raises(monkeypatch):
    monkeypatch.delenv("OPENAI_API_KEY", raising=False)
    with pytest.raises(APIKeyMissingError):
        BridgeConfig.from_dict(
            {
                "llm": {"provider": "openai", "model": "gpt4o"},
                "mcp": {"url": "http://localhost:3000", "transport": "streamable_http"},
                "prompt": {"system": "hi"},
            }
        )


def test_mcp_url_and_command_conflict():
    with pytest.raises(ConfigValidationError):
        BridgeConfig.from_dict(
            {
                "llm": {"provider": "openai", "model": "gpt4o", "api_key": "k"},
                "mcp": {"url": "http://localhost:3000", "command": "python", "transport": "auto"},
                "prompt": {"system": "hi"},
            }
        )


def test_servers_override_top_level_url():
    cfg = BridgeConfig.from_dict(
        {
            "llm": {"provider": "openai", "model": "gpt4o", "api_key": "k"},
            "mcp": {
                "url": "http://should-be-ignored",
                "transport": "streamable_http",
                "servers": [
                    {
                        "name": "s1",
                        "command": "python",
                        "args": ["server.py"],
                        "transport": "stdio",
                    }
                ],
            },
            "prompt": {"system": "hi"},
        }
    )
    assert cfg.mcp.servers is not None
    assert cfg.mcp.url is None
    assert len(cfg.mcp.servers) == 1
    assert cfg.mcp.servers[0].name == "s1"

