"""Tests for gateway router."""
import pytest
from unittest.mock import AsyncMock
from greymatter_core.router import GatewayRouter
from greymatter_core.gateway import CompletionResult


def _mock_gateway(provider: str, available: bool = True):
    gw = AsyncMock()
    gw.provider = provider
    gw.model_name = f"{provider}-model"
    gw.check_available = AsyncMock(return_value=available)
    gw.complete = AsyncMock(return_value=CompletionResult(
        content=f"from {provider}", model=f"{provider}-model",
        provider=provider, tokens_used=10, latency_ms=100, cost_estimate=0.0,
    ))
    return gw


@pytest.mark.asyncio
async def test_routes_to_available_provider():
    ollama = _mock_gateway("ollama", available=True)
    router = GatewayRouter({"ollama": ollama})
    result = await router.route([{"role": "user", "content": "hello"}])
    assert result.provider == "ollama"


@pytest.mark.asyncio
async def test_prefers_claude_when_available():
    ollama = _mock_gateway("ollama", available=True)
    claude = _mock_gateway("claude", available=True)
    router = GatewayRouter({"ollama": ollama, "claude": claude})
    result = await router.route([{"role": "user", "content": "hello"}])
    assert result.provider == "claude"


@pytest.mark.asyncio
async def test_falls_back_to_ollama_when_claude_unavailable():
    ollama = _mock_gateway("ollama", available=True)
    claude = _mock_gateway("claude", available=False)
    router = GatewayRouter({"ollama": ollama, "claude": claude})
    result = await router.route([{"role": "user", "content": "hello"}])
    assert result.provider == "ollama"


@pytest.mark.asyncio
async def test_prefer_local():
    ollama = _mock_gateway("ollama", available=True)
    claude = _mock_gateway("claude", available=True)
    router = GatewayRouter({"ollama": ollama, "claude": claude})
    result = await router.route([{"role": "user", "content": "hello"}], prefer="local")
    assert result.provider == "ollama"


@pytest.mark.asyncio
async def test_no_providers_available():
    ollama = _mock_gateway("ollama", available=False)
    router = GatewayRouter({"ollama": ollama})
    with pytest.raises(RuntimeError, match="No LLM providers available"):
        await router.route([{"role": "user", "content": "hello"}])
