"""LLM router for model selection."""

from typing import Optional

from ..config import Config, ModelConfig
from .base import DeepSeekProvider, KimiProvider, LLMProvider, OllamaProvider, OpenAIProvider
from .local_parser import LocalIntentParser


class LLMRouter:
    """Routes requests to the appropriate LLM provider."""

    PROVIDERS = {
        "kimi": KimiProvider,
        "deepseek": DeepSeekProvider,
        "openai": OpenAIProvider,
        "ollama": OllamaProvider,
    }

    def __init__(self, config: Optional[Config] = None):
        self.config = config or Config.load()
        self._providers: dict[str, LLMProvider] = {}

    def get_provider(self, model_name: Optional[str] = None) -> LLMProvider:
        """Get or create a provider instance."""
        model_name = model_name or self.config.default_model

        # Special case: local parser (no API key needed)
        if model_name == "local":
            return LocalProvider()

        if model_name not in self._providers:
            model_config = self.config.get_model_config(model_name)
            if not model_config:
                raise ValueError(
                    f"Model '{model_name}' not configured. "
                    f"Run: surfai config --model {model_name} --key <api_key>"
                )

            provider_class = self.PROVIDERS.get(model_name)
            if not provider_class:
                raise ValueError(f"Unknown model: {model_name}")

            self._providers[model_name] = provider_class(model_config)

        return self._providers[model_name]

    def list_available_models(self) -> list[str]:
        """List all configured models."""
        return list(self.config.models.keys())

    async def close_all(self) -> None:
        """Close all provider connections."""
        for provider in self._providers.values():
            await provider.close()
        self._providers.clear()


class LocalProvider:
    """
    Local rule-based provider - no API key required.
    """

    def __init__(self):
        pass

    async def understand(self, instruction: str):
        """Parse instruction using local parser."""
        return LocalIntentParser.parse(instruction)

    async def chat(self, messages: list[dict[str, str]]) -> str:
        """Not supported in local mode."""
        return "Local mode does not support chat."

    async def extract_from_page(self, html_content: str, instruction: str) -> str:
        """Not supported in local mode."""
        return "Local mode does not support page extraction."

    async def close(self) -> None:
        """Nothing to close."""
        pass
