"""Gateway Router -- routes to best available LLM.

Priority order (default): claude > openrouter > ollama
Override with prefer="local" to always use Ollama.
"""
from .gateway import CompletionResult, LLMGateway

# Default priority: highest capability first
PROVIDER_PRIORITY = ["claude", "openrouter", "ollama"]


class GatewayRouter:
    """Routes completions to the best available LLM provider."""

    def __init__(self, gateways: dict[str, LLMGateway]):
        self.gateways = gateways

    async def route(
        self,
        messages: list[dict],
        prefer: str | None = None,
        **kwargs,
    ) -> CompletionResult:
        """Route to best available provider.

        Args:
            messages: Chat messages.
            prefer: "local" forces Ollama, "best" uses priority order.
            **kwargs: Passed to the gateway's complete method.
        """
        if prefer == "local" and "ollama" in self.gateways:
            gw = self.gateways["ollama"]
            if await gw.check_available():
                return await gw.complete(messages, **kwargs)

        # Try providers in priority order
        for provider_name in PROVIDER_PRIORITY:
            if provider_name in self.gateways:
                gw = self.gateways[provider_name]
                if await gw.check_available():
                    return await gw.complete(messages, **kwargs)

        # Try any remaining providers not in priority list
        for name, gw in self.gateways.items():
            if name not in PROVIDER_PRIORITY:
                if await gw.check_available():
                    return await gw.complete(messages, **kwargs)

        raise RuntimeError("No LLM providers available")

    async def list_available(self) -> list[str]:
        """List currently available providers."""
        available = []
        for name, gw in self.gateways.items():
            if await gw.check_available():
                available.append(name)
        return available
