"""Slices AI Infrastructure Service Resource API."""

from httpx import Client, HTTPError
from msgspec.json import Decoder as JsonDecoder
from slices_clientlib_core.base.exceptions import from_httpx_exception

from .schema.worker import Cluster, Slave

_slave_list_decoder = JsonDecoder(list[Slave])
_cluster_list_decoder = JsonDecoder(list[Cluster])


class AIWorkersClient:
    """AI Infrastructure Service Workers API Client."""

    API_BASE_PATH = "/apis/ai.slices-ri.eu/v1/"

    def __init__(self, client: Client) -> None:
        """Create AI Infrastructure Service Workers Client."""

        self._client = client

        self._base_path = f"{self.API_BASE_PATH}"

        assert client.base_url is not None, "Expected base_url to be set"

    def list_clusters(self) -> list[Cluster]:
        """List clusters."""

        response = self._client.get(f"{self._base_path}clusters")

        try:
            response.raise_for_status()
            return _cluster_list_decoder.decode(response.content)
        except HTTPError as err:
            raise from_httpx_exception(err) from err

    def list_slaves(self) -> list[Slave]:
        """List workers."""

        response = self._client.get(f"{self._base_path}slaves")

        try:
            response.raise_for_status()
            return _slave_list_decoder.decode(response.content)
        except HTTPError as err:
            raise from_httpx_exception(err) from err
