"""LLM Models resource."""

from __future__ import annotations

from typing import Any, Dict, Generator, List, Optional, TYPE_CHECKING

from netorca_sdk.v2.base import BaseResource
from netorca_sdk.v2.models.llm_model import LLMModel

if TYPE_CHECKING:
    from netorca_sdk.v2.client import NetOrcaClient


class LLMModelsResource(BaseResource):
    """
    LLM Models resource.

    Provides access to LLM model configuration management.

    Example:
        ```python
        # List all LLM models
        for model in client.llm_models.list():
            print(model.name, model.provider)

        # Create a new LLM model
        model = client.llm_models.create({
            "name": "GPT-4",
            "provider": "openai",
            "model_id": "gpt-4",
            "api_key": "sk-..."
        })

        # Test connection
        result = client.llm_models.test_connection({
            "provider": "openai",
            "model_id": "gpt-4",
            "api_key": "sk-..."
        })
        ```
    """

    endpoint = "llm_models"
    model_class = LLMModel

    def _build_ai_url(self, path: str) -> str:
        """Build URL for AI endpoints."""
        return f"{self.client.fqdn}/ai/{path}/"

    def list(self, **filters) -> Generator[LLMModel, None, None]:
        """List all LLM models."""
        url = self._build_ai_url(self.endpoint)
        next_url: Optional[str] = url

        while next_url:
            response = self.client.auth.get(next_url, filters=filters if next_url == url else None)
            data = self.client._handle_response(response, self.endpoint)

            for item in data.get('results', []):
                yield self._to_model(item)

            next_url = data.get('next')

    def filter(self, **filters) -> List[LLMModel]:
        """Get LLM models as a list with filters."""
        return list(self.list(**filters))

    def get(self, id: int) -> LLMModel:
        """Get a specific LLM model."""
        url = self._build_ai_url(f"{self.endpoint}/{id}")
        response = self.client.auth.get(url)
        data = self.client._handle_response(response, self.endpoint)
        return self._to_model(data)

    def create(self, data: Dict[str, Any]) -> LLMModel:
        """Create a new LLM model."""
        url = self._build_ai_url(self.endpoint)
        response = self.client.auth.post(url, data=data)
        result = self.client._handle_response(response, self.endpoint)
        return self._to_model(result)

    def update(self, id: int, data: Dict[str, Any], partial: bool = True) -> LLMModel:
        """Update an LLM model."""
        url = self._build_ai_url(f"{self.endpoint}/{id}")
        if partial:
            response = self.client.auth.patch(url, data=data)
        else:
            response = self.client.auth.put(url, data=data)
        result = self.client._handle_response(response, self.endpoint)
        return self._to_model(result)

    def delete(self, id: int) -> Dict[str, Any]:
        """Delete an LLM model."""
        url = self._build_ai_url(f"{self.endpoint}/{id}")
        response = self.client.auth.delete(url)
        return self.client._handle_response(response, self.endpoint)

    def test_connection(self, data: Dict[str, Any]) -> Dict[str, Any]:
        """Test connection to an LLM provider.

        Args:
            data: Connection configuration including provider, model_id, api_key, etc.

        Returns:
            Test result with connection status
        """
        url = self._build_ai_url(f"{self.endpoint}/test_connection")
        response = self.client.auth.post(url, data=data)
        return self.client._handle_response(response, self.endpoint)

    def get_active(self) -> List[LLMModel]:
        """Get all active LLM models."""
        return [m for m in self.list() if m.is_active]
