"""Service models for the Danube SDK."""

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

from pydantic import BaseModel, Field


ServiceType = Literal["mcp_server", "api", "internal", "website"]


class Service(BaseModel):
    """A service provider in Danube.

    Services represent API providers or MCP servers that offer tools
    for execution through the Danube platform.
    """

    id: str
    name: str
    description: str = ""
    summary: str = ""
    version: str = ""
    service_type: ServiceType = "api"

    # Connection info
    url: Optional[str] = None
    is_connected: bool = False

    # Counts and metadata
    tool_count: int = 0
    is_verified: bool = False
    visibility: str = "public"

    # Marketplace
    category: Optional[str] = None
    verification_tier: str = "unverified"

    # Optional detailed info
    logo: str = ""
    documentation_url: Optional[str] = None
    requires_credentials: bool = False

    model_config = {"extra": "ignore"}

    @classmethod
    def from_api_response(cls, data: Dict[str, Any]) -> "Service":
        """Create a Service from API response data.

        Args:
            data: Raw API response dictionary.

        Returns:
            Service instance.
        """
        return cls(
            id=data.get("id", ""),
            name=data.get("name", ""),
            description=data.get("description", "") or data.get("summary", ""),
            summary=data.get("summary", ""),
            version=data.get("version", ""),
            service_type=data.get("service_type", "api"),
            url=data.get("mcp_server_url") or data.get("api_base_url"),
            is_connected=data.get("mcp_connected", False),
            tool_count=data.get("tool_count", 0),
            is_verified=data.get("is_verified", False),
            visibility=data.get("visibility", "public"),
            category=data.get("category"),
            verification_tier=data.get("verification_tier", "unverified"),
            logo=data.get("logo", ""),
            documentation_url=data.get("documentation_url"),
            requires_credentials=bool(data.get("credential_schema")),
        )


class ServiceToolsResult(BaseModel):
    """Result from get_service_tools with configuration info.

    When a service requires credentials that haven't been configured,
    this result will indicate what configuration is needed.
    """

    tools: List["Tool"] = Field(default_factory=list)
    needs_configuration: bool = False
    skipped: bool = False
    configuration_required: Optional[Dict[str, Any]] = None

    @property
    def configuration_url(self) -> Optional[str]:
        """Get the URL to configure credentials for this service."""
        if self.configuration_required:
            return self.configuration_required.get("configuration_url")
        return None


# Import Tool here to avoid circular import
from danube.models.tools import Tool  # noqa: E402

ServiceToolsResult.model_rebuild()
