"""Stream manager for handling streams operations."""

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

from ..types import ListResponse, OutputStream

if TYPE_CHECKING:
    from ..client import ToothFairyClient


class StreamManager:
    """Manager for streams operations.

    This manager provides methods to create, update, and manage streams.

    Example:
        >>> client = ToothFairyClient(api_key="...", workspace_id="...")
        >>> stream = client.streams.get(...)
    """

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

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

    def get(self, stream_id: str) -> OutputStream:
        """Get a stream by ID.

        Args:
            stream_id: ID of the stream to retrieve.

        Returns:
            The OutputStream object.
        """
        response = self._client.request("GET", f"/stream/get/{stream_id}")
        return OutputStream.from_dict(response)

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

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

        Returns:
            A ListResponse containing the streams.
        """
        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", "/stream/list", params=params)

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

        return ListResponse(items=items)

    def get_by_type(self, stream_type: str) -> List[OutputStream]:
        """Get streams by type.

        Args:
            stream_type: Type of stream to filter by.

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

    def get_by_status(self, status: str) -> List[OutputStream]:
        """Get streams by status.

        Args:
            status: Status to filter by.

        Returns:
            A list of OutputStream objects with the specified status.
        """
        result = self.list()
        return [stream for stream in result.items if stream.status == status]
