"""Connection manager for handling connections (Hosting) operations."""

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

from ..types import Connection, Hosting, HostingType, ListResponse

if TYPE_CHECKING:
    from ..client import ToothFairyClient


class ConnectionManager:
    """Manager for connections (Hosting) operations.

    This manager provides methods to create, update, and manage connections (Hostings).
    Note: In the API, /connection/* endpoints map to Hosting entities.

    Example:
        >>> client = ToothFairyClient(api_key="...", workspace_id="...")
        >>> connection = client.connections.create(
        ...     name="OpenAI Connection",
        ...     type="openai",
        ...     endpoint="https://api.openai.com",
        ... )
    """

    def __init__(self, client: "ToothFairyClient"):
        """Initialize the ConnectionManager.

        Args:
            client: The ToothFairyClient instance.
        """
        self._client = client

    def create(
        self,
        name: str,
        type: HostingType,
        endpoint: Optional[str] = None,
        model_name: Optional[str] = None,
        base_model: Optional[str] = None,
        custom_model: bool = False,
        api_version: Optional[str] = None,
        token_secret: Optional[str] = None,
        description: Optional[str] = None,
    ) -> Hosting:
        """Create a new connection (Hosting).

        Args:
            name: Connection name.
            type: Hosting type (azure_openai, aws, local, google, anthropic, together, tf, replicate, azure, openai, groq, ollama).
            endpoint: API endpoint URL.
            model_name: Model name to use.
            base_model: Base model identifier.
            custom_model: Whether this is a custom model.
            api_version: API version (for Azure OpenAI).
            token_secret: Secret name for API token.
            description: Connection description.

        Returns:
            The created Hosting object.
        """
        data: Dict[str, Any] = {
            "name": name,
            "type": type,
            "customModel": custom_model,
        }

        if endpoint is not None:
            data["endpoint"] = endpoint
        if model_name is not None:
            data["modelName"] = model_name
        if base_model is not None:
            data["baseModel"] = base_model
        if api_version is not None:
            data["apiVersion"] = api_version
        if token_secret is not None:
            data["tokenSecret"] = token_secret
        if description is not None:
            data["description"] = description

        response = self._client.request("POST", "/connection/create", data=data)
        return Hosting.from_dict(response)

    def update(
        self,
        connection_id: str,
        **kwargs: Any,
    ) -> Hosting:
        """Update a connection (Hosting).

        Args:
            connection_id: ID of the connection to update.
            **kwargs: Fields to update (name, type, endpoint, modelName, baseModel, customModel, apiVersion, tokenSecret, description).

        Returns:
            The updated Hosting object.
        """
        data: Dict[str, Any] = {"id": connection_id}
        data.update(kwargs)
        response = self._client.request("POST", "/connection/update", data=data)
        return Hosting.from_dict(response)

    def delete(self, connection_id: str) -> Dict[str, bool]:
        """Delete a connection.

        Args:
            connection_id: ID of the connection to delete.

        Returns:
            A dictionary with success status.
        """
        self._client.request("DELETE", f"/connection/delete/{connection_id}")
        return {"success": True}

    def get(self, connection_id: str) -> Hosting:
        """Get a connection by ID.

        Args:
            connection_id: ID of the connection to retrieve.

        Returns:
            The Hosting object.
        """
        response = self._client.request("GET", f"/connection/get/{connection_id}")
        return Hosting.from_dict(response)

    def list(
        self,
        limit: Optional[int] = None,
        offset: Optional[int] = None,
    ) -> ListResponse:
        """List all connections.

        Args:
            limit: Maximum number of connections to return.
            offset: Number of connections to skip.

        Returns:
            A ListResponse containing the connections.
        """
        params: Dict[str, Any] = {}
        if limit is not None:
            params["limit"] = limit
        if offset is not None:
            params["offset"] = offset

        response = self._client.request("GET", "/connection/list", params=params)

        items = []
        if isinstance(response, list):
            items = [Hosting.from_dict(item) for item in response]
        elif isinstance(response, dict):
            items = [Hosting.from_dict(item) for item in response.get("items", [])]

        return ListResponse(items=items)

    def get_by_type(self, hosting_type: HostingType) -> List[Hosting]:
        """Get connections by hosting type.

        Args:
            hosting_type: Hosting type to filter by (openai, azure, anthropic, etc.).

        Returns:
            A list of Hosting objects with the specified type.
        """
        result = self.list()
        return [conn for conn in result.items if conn.type == hosting_type]

    def search(self, search_term: str) -> List[Hosting]:
        """Search connections by name.

        Args:
            search_term: Term to search for in connection names.

        Returns:
            A list of matching Hosting objects.
        """
        all_connections = self.list()
        search_lower = search_term.lower()
        return [conn for conn in all_connections.items if search_lower in conn.name.lower()]
