from typing import Optional
from ..transport import SyncTransport
from ..models.serverless import ServerlessModel, ServerlessModelsResponse


class ServerlessResource:
    def __init__(self, transport: SyncTransport):
        self._transport = transport

    def list_models(
        self,
        modality: Optional[str] = None,
        *,
        search: Optional[str] = None,
        highlight: Optional[str] = None,
        use_case: Optional[str] = None,
        model_family: Optional[str] = None,
        filter_logic: str = "or",
        include_tag_counts: bool = True,
    ) -> ServerlessModelsResponse:
        """List available serverless models with optional filtering.

        Args:
            modality: Filter by modality (comma-separated),
                e.g. "text_generation", "text_to_image", "multimodal".
            search: Search across all tag categories.
            highlight: Filter by highlight tags (comma-separated),
                e.g. "free", "recently_added", "featured".
            use_case: Filter by use case (comma-separated),
                e.g. "best_role_play", "best_image_generation".
            model_family: Filter by model family (comma-separated),
                e.g. "Manta", "OpenAI", "Gemini", "Deepseek".
            filter_logic: Logic for combining comma-separated values:
                "and" (all must match) or "or" (any must match).
            include_tag_counts: Include available tag counts in response.

        Returns:
            ServerlessModelsResponse with models list, count, and optional tag_counts.
        """
        params = {"include_tag_counts": str(include_tag_counts).lower()}
        if modality is not None:
            params["modality"] = modality
        if search is not None:
            params["search"] = search
        if highlight is not None:
            params["highlight"] = highlight
        if use_case is not None:
            params["use_case"] = use_case
        if model_family is not None:
            params["model_family"] = model_family
        if filter_logic != "or":
            params["filter_logic"] = filter_logic

        # The serverless endpoint uses /api/v1/ instead of the standard /v1/ base.
        data = self._transport.request(
            "GET",
            "/api/v1/serverless/models/filter",
            params=params,
            base_url_override=self._transport.base_url.replace("/v1", ""),
        )
        # Response: {"data": {"models": [...], "count": N, "tag_counts": {...}}}
        inner = data.get("data", data)
        return ServerlessModelsResponse(**inner)
