"""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.news import News

_news_decoder = JsonDecoder(News)
_news_list_decoder = JsonDecoder(list[News])


class AINewsClient:
    """AI Infrastructure Service News API Client."""

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

    def __init__(self, client: Client) -> None:
        """Create AI Infrastructure Service News 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 get(self, id: str) -> News:
        """Get news by ID."""
        response = self._client.get(f"{self._base_path}{id}")

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

    def list(self) -> list[News]:
        """List news."""

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

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