# This file was auto-generated by Fern from our API Definition.

import typing
from json.decoder import JSONDecodeError

from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.http_response import AsyncHttpResponse, HttpResponse
from ..core.jsonable_encoder import jsonable_encoder
from ..core.pagination import AsyncPager, SyncPager
from ..core.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..types.empty_response import EmptyResponse
from ..types.get_model_version_response import GetModelVersionResponse
from ..types.list_model_versions_response import ListModelVersionsResponse
from ..types.model_version import ModelVersion

# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)


class RawModelVersionsClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._client_wrapper = client_wrapper

    def apply_tags(
        self,
        *,
        model_version_id: str,
        tags: typing.Sequence[str],
        force: typing.Optional[bool] = False,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[EmptyResponse]:
        """
        Parameters
        ----------
        model_version_id : str

        tags : typing.Sequence[str]

        force : typing.Optional[bool]

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[EmptyResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/ml/v1/model-versions/tags",
            method="PUT",
            json={
                "model_version_id": model_version_id,
                "tags": tags,
                "force": force,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    EmptyResponse,
                    parse_obj_as(
                        type_=EmptyResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def get(
        self, id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[GetModelVersionResponse]:
        """
        Get model version API

        Parameters
        ----------
        id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[GetModelVersionResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/ml/v1/model-versions/{jsonable_encoder(id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetModelVersionResponse,
                    parse_obj_as(
                        type_=GetModelVersionResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def delete(
        self, id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[EmptyResponse]:
        """
        Delete model versions API

        Parameters
        ----------
        id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[EmptyResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/ml/v1/model-versions/{jsonable_encoder(id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    EmptyResponse,
                    parse_obj_as(
                        type_=EmptyResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def list(
        self,
        *,
        tag: typing.Optional[str] = None,
        fqn: typing.Optional[str] = None,
        model_id: typing.Optional[str] = None,
        ml_repo_id: typing.Optional[str] = None,
        name: typing.Optional[str] = None,
        version: typing.Optional[int] = None,
        run_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        run_steps: typing.Optional[typing.Union[int, typing.Sequence[int]]] = None,
        offset: typing.Optional[int] = 0,
        limit: typing.Optional[int] = 100,
        include_internal_metadata: typing.Optional[bool] = False,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> SyncPager[ModelVersion, ListModelVersionsResponse]:
        """
        List model version API

        Parameters
        ----------
        tag : typing.Optional[str]

        fqn : typing.Optional[str]

        model_id : typing.Optional[str]

        ml_repo_id : typing.Optional[str]

        name : typing.Optional[str]

        version : typing.Optional[int]

        run_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]

        run_steps : typing.Optional[typing.Union[int, typing.Sequence[int]]]

        offset : typing.Optional[int]

        limit : typing.Optional[int]

        include_internal_metadata : typing.Optional[bool]

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        SyncPager[ModelVersion, ListModelVersionsResponse]
            Successful Response
        """
        offset = offset if offset is not None else 0

        _response = self._client_wrapper.httpx_client.request(
            "api/ml/v1/model-versions",
            method="GET",
            params={
                "tag": tag,
                "fqn": fqn,
                "model_id": model_id,
                "ml_repo_id": ml_repo_id,
                "name": name,
                "version": version,
                "run_ids": run_ids,
                "run_steps": run_steps,
                "offset": offset,
                "limit": limit,
                "include_internal_metadata": include_internal_metadata,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListModelVersionsResponse,
                    parse_obj_as(
                        type_=ListModelVersionsResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _items = _parsed_response.data
                _has_next = True
                _get_next = lambda: self.list(
                    tag=tag,
                    fqn=fqn,
                    model_id=model_id,
                    ml_repo_id=ml_repo_id,
                    name=name,
                    version=version,
                    run_ids=run_ids,
                    run_steps=run_steps,
                    offset=offset + len(_items),
                    limit=limit,
                    include_internal_metadata=include_internal_metadata,
                    request_options=request_options,
                )
                return SyncPager(has_next=_has_next, items=_items, get_next=_get_next, response=_parsed_response)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


class AsyncRawModelVersionsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def apply_tags(
        self,
        *,
        model_version_id: str,
        tags: typing.Sequence[str],
        force: typing.Optional[bool] = False,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[EmptyResponse]:
        """
        Parameters
        ----------
        model_version_id : str

        tags : typing.Sequence[str]

        force : typing.Optional[bool]

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[EmptyResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/ml/v1/model-versions/tags",
            method="PUT",
            json={
                "model_version_id": model_version_id,
                "tags": tags,
                "force": force,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    EmptyResponse,
                    parse_obj_as(
                        type_=EmptyResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def get(
        self, id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[GetModelVersionResponse]:
        """
        Get model version API

        Parameters
        ----------
        id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[GetModelVersionResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/ml/v1/model-versions/{jsonable_encoder(id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetModelVersionResponse,
                    parse_obj_as(
                        type_=GetModelVersionResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def delete(
        self, id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[EmptyResponse]:
        """
        Delete model versions API

        Parameters
        ----------
        id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[EmptyResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/ml/v1/model-versions/{jsonable_encoder(id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    EmptyResponse,
                    parse_obj_as(
                        type_=EmptyResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def list(
        self,
        *,
        tag: typing.Optional[str] = None,
        fqn: typing.Optional[str] = None,
        model_id: typing.Optional[str] = None,
        ml_repo_id: typing.Optional[str] = None,
        name: typing.Optional[str] = None,
        version: typing.Optional[int] = None,
        run_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        run_steps: typing.Optional[typing.Union[int, typing.Sequence[int]]] = None,
        offset: typing.Optional[int] = 0,
        limit: typing.Optional[int] = 100,
        include_internal_metadata: typing.Optional[bool] = False,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncPager[ModelVersion, ListModelVersionsResponse]:
        """
        List model version API

        Parameters
        ----------
        tag : typing.Optional[str]

        fqn : typing.Optional[str]

        model_id : typing.Optional[str]

        ml_repo_id : typing.Optional[str]

        name : typing.Optional[str]

        version : typing.Optional[int]

        run_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]

        run_steps : typing.Optional[typing.Union[int, typing.Sequence[int]]]

        offset : typing.Optional[int]

        limit : typing.Optional[int]

        include_internal_metadata : typing.Optional[bool]

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncPager[ModelVersion, ListModelVersionsResponse]
            Successful Response
        """
        offset = offset if offset is not None else 0

        _response = await self._client_wrapper.httpx_client.request(
            "api/ml/v1/model-versions",
            method="GET",
            params={
                "tag": tag,
                "fqn": fqn,
                "model_id": model_id,
                "ml_repo_id": ml_repo_id,
                "name": name,
                "version": version,
                "run_ids": run_ids,
                "run_steps": run_steps,
                "offset": offset,
                "limit": limit,
                "include_internal_metadata": include_internal_metadata,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListModelVersionsResponse,
                    parse_obj_as(
                        type_=ListModelVersionsResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _items = _parsed_response.data
                _has_next = True

                async def _get_next():
                    return await self.list(
                        tag=tag,
                        fqn=fqn,
                        model_id=model_id,
                        ml_repo_id=ml_repo_id,
                        name=name,
                        version=version,
                        run_ids=run_ids,
                        run_steps=run_steps,
                        offset=offset + len(_items),
                        limit=limit,
                        include_internal_metadata=include_internal_metadata,
                        request_options=request_options,
                    )

                return AsyncPager(has_next=_has_next, items=_items, get_next=_get_next, response=_parsed_response)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
