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

import typing
from ..core.client_wrapper import SyncClientWrapper
from ..core.request_options import RequestOptions
from ..types.prediction import Prediction
from ..core.unchecked_base_model import construct_type
from json.decoder import JSONDecodeError
from ..core.api_error import ApiError
from ..core.jsonable_encoder import jsonable_encoder
from ..core.client_wrapper import AsyncClientWrapper

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


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

    def list(
        self,
        *,
        project: typing.Optional[int] = None,
        task: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.List[Prediction]:
        """
        List all predictions and their IDs.

        Parameters
        ----------
        project : typing.Optional[int]
            Filter predictions by project ID

        task : typing.Optional[int]
            Filter predictions by task ID

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

        Returns
        -------
        typing.List[Prediction]
            Predictions list

        Examples
        --------
        from label_studio_sdk import LabelStudio

        client = LabelStudio(
            api_key="YOUR_API_KEY",
        )
        client.predictions.list()
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/predictions/",
            method="GET",
            params={
                "project": project,
                "task": task,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    typing.List[Prediction],
                    construct_type(
                        type_=typing.List[Prediction],  # type: ignore
                        object_=_response.json(),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def create(
        self,
        *,
        model_version: typing.Optional[str] = OMIT,
        result: typing.Optional[typing.Sequence[typing.Dict[str, typing.Optional[typing.Any]]]] = OMIT,
        score: typing.Optional[float] = OMIT,
        task: typing.Optional[int] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Prediction:
        """
        Create a prediction for a specific task.

        Parameters
        ----------
        model_version : typing.Optional[str]
            Model version - tag for predictions that can be used to filter tasks in Data Manager, as well as select specific model version for showing preannotations in the labeling interface

        result : typing.Optional[typing.Sequence[typing.Dict[str, typing.Optional[typing.Any]]]]
            Prediction result in JSON format. Read more about the format in [the Label Studio documentation.](https://labelstud.io/guide/predictions)

        score : typing.Optional[float]
            Prediction score. Can be used in Data Manager to sort task by model confidence. Task with the lowest score will be shown first.

        task : typing.Optional[int]
            Task ID for which the prediction is created

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

        Returns
        -------
        Prediction
            Created prediction

        Examples
        --------
        from label_studio_sdk import LabelStudio

        client = LabelStudio(
            api_key="YOUR_API_KEY",
        )
        client.predictions.create(
            model_version="yolo-v8",
            result=[
                {
                    "from_name": "bboxes",
                    "image_rotation": 0,
                    "original_height": 1080,
                    "original_width": 1920,
                    "to_name": "image",
                    "type": "rectanglelabels",
                    "value": {
                        "height": 60,
                        "rotation": 0,
                        "values": {"rectanglelabels": ["Person"]},
                        "width": 50,
                        "x": 20,
                        "y": 30,
                    },
                }
            ],
            score=0.95,
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/predictions/",
            method="POST",
            json={
                "model_version": model_version,
                "result": result,
                "score": score,
                "task": task,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Prediction,
                    construct_type(
                        type_=Prediction,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def get(self, id: int, *, request_options: typing.Optional[RequestOptions] = None) -> Prediction:
        """
        Get details about a specific prediction by its ID.

        Parameters
        ----------
        id : int
            Prediction ID

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

        Returns
        -------
        Prediction
            Prediction details

        Examples
        --------
        from label_studio_sdk import LabelStudio

        client = LabelStudio(
            api_key="YOUR_API_KEY",
        )
        client.predictions.get(
            id=1,
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/predictions/{jsonable_encoder(id)}/",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Prediction,
                    construct_type(
                        type_=Prediction,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def delete(self, id: int, *, request_options: typing.Optional[RequestOptions] = None) -> None:
        """
        Delete a prediction by prediction ID.

        Parameters
        ----------
        id : int
            Prediction ID

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

        Returns
        -------
        None

        Examples
        --------
        from label_studio_sdk import LabelStudio

        client = LabelStudio(
            api_key="YOUR_API_KEY",
        )
        client.predictions.delete(
            id=1,
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/predictions/{jsonable_encoder(id)}/",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def update(
        self,
        id: int,
        *,
        model_version: typing.Optional[str] = OMIT,
        result: typing.Optional[typing.Sequence[typing.Dict[str, typing.Optional[typing.Any]]]] = OMIT,
        score: typing.Optional[float] = OMIT,
        task: typing.Optional[int] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Prediction:
        """
        Update prediction data by prediction ID.

        Parameters
        ----------
        id : int
            Prediction ID

        model_version : typing.Optional[str]
            Model version - tag for predictions that can be used to filter tasks in Data Manager, as well as select specific model version for showing preannotations in the labeling interface

        result : typing.Optional[typing.Sequence[typing.Dict[str, typing.Optional[typing.Any]]]]
            Prediction result in JSON format. Read more about the format in [the Label Studio documentation.](https://labelstud.io/guide/predictions)

        score : typing.Optional[float]
            Prediction score. Can be used in Data Manager to sort task by model confidence. Task with the lowest score will be shown first.

        task : typing.Optional[int]
            Task ID for which the prediction is created

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

        Returns
        -------
        Prediction
            Updated prediction

        Examples
        --------
        from label_studio_sdk import LabelStudio

        client = LabelStudio(
            api_key="YOUR_API_KEY",
        )
        client.predictions.update(
            id=1,
            model_version="yolo-v8",
            result=[
                {
                    "from_name": "bboxes",
                    "image_rotation": 0,
                    "original_height": 1080,
                    "original_width": 1920,
                    "to_name": "image",
                    "type": "rectanglelabels",
                    "value": {
                        "height": 60,
                        "rotation": 0,
                        "values": {"rectanglelabels": ["Person"]},
                        "width": 50,
                        "x": 20,
                        "y": 30,
                    },
                }
            ],
            score=0.95,
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/predictions/{jsonable_encoder(id)}/",
            method="PATCH",
            json={
                "model_version": model_version,
                "result": result,
                "score": score,
                "task": task,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Prediction,
                    construct_type(
                        type_=Prediction,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)


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

    async def list(
        self,
        *,
        project: typing.Optional[int] = None,
        task: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.List[Prediction]:
        """
        List all predictions and their IDs.

        Parameters
        ----------
        project : typing.Optional[int]
            Filter predictions by project ID

        task : typing.Optional[int]
            Filter predictions by task ID

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

        Returns
        -------
        typing.List[Prediction]
            Predictions list

        Examples
        --------
        import asyncio

        from label_studio_sdk import AsyncLabelStudio

        client = AsyncLabelStudio(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.predictions.list()


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/predictions/",
            method="GET",
            params={
                "project": project,
                "task": task,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    typing.List[Prediction],
                    construct_type(
                        type_=typing.List[Prediction],  # type: ignore
                        object_=_response.json(),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def create(
        self,
        *,
        model_version: typing.Optional[str] = OMIT,
        result: typing.Optional[typing.Sequence[typing.Dict[str, typing.Optional[typing.Any]]]] = OMIT,
        score: typing.Optional[float] = OMIT,
        task: typing.Optional[int] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Prediction:
        """
        Create a prediction for a specific task.

        Parameters
        ----------
        model_version : typing.Optional[str]
            Model version - tag for predictions that can be used to filter tasks in Data Manager, as well as select specific model version for showing preannotations in the labeling interface

        result : typing.Optional[typing.Sequence[typing.Dict[str, typing.Optional[typing.Any]]]]
            Prediction result in JSON format. Read more about the format in [the Label Studio documentation.](https://labelstud.io/guide/predictions)

        score : typing.Optional[float]
            Prediction score. Can be used in Data Manager to sort task by model confidence. Task with the lowest score will be shown first.

        task : typing.Optional[int]
            Task ID for which the prediction is created

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

        Returns
        -------
        Prediction
            Created prediction

        Examples
        --------
        import asyncio

        from label_studio_sdk import AsyncLabelStudio

        client = AsyncLabelStudio(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.predictions.create(
                model_version="yolo-v8",
                result=[
                    {
                        "from_name": "bboxes",
                        "image_rotation": 0,
                        "original_height": 1080,
                        "original_width": 1920,
                        "to_name": "image",
                        "type": "rectanglelabels",
                        "value": {
                            "height": 60,
                            "rotation": 0,
                            "values": {"rectanglelabels": ["Person"]},
                            "width": 50,
                            "x": 20,
                            "y": 30,
                        },
                    }
                ],
                score=0.95,
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/predictions/",
            method="POST",
            json={
                "model_version": model_version,
                "result": result,
                "score": score,
                "task": task,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Prediction,
                    construct_type(
                        type_=Prediction,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def get(self, id: int, *, request_options: typing.Optional[RequestOptions] = None) -> Prediction:
        """
        Get details about a specific prediction by its ID.

        Parameters
        ----------
        id : int
            Prediction ID

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

        Returns
        -------
        Prediction
            Prediction details

        Examples
        --------
        import asyncio

        from label_studio_sdk import AsyncLabelStudio

        client = AsyncLabelStudio(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.predictions.get(
                id=1,
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/predictions/{jsonable_encoder(id)}/",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Prediction,
                    construct_type(
                        type_=Prediction,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def delete(self, id: int, *, request_options: typing.Optional[RequestOptions] = None) -> None:
        """
        Delete a prediction by prediction ID.

        Parameters
        ----------
        id : int
            Prediction ID

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

        Returns
        -------
        None

        Examples
        --------
        import asyncio

        from label_studio_sdk import AsyncLabelStudio

        client = AsyncLabelStudio(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.predictions.delete(
                id=1,
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/predictions/{jsonable_encoder(id)}/",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def update(
        self,
        id: int,
        *,
        model_version: typing.Optional[str] = OMIT,
        result: typing.Optional[typing.Sequence[typing.Dict[str, typing.Optional[typing.Any]]]] = OMIT,
        score: typing.Optional[float] = OMIT,
        task: typing.Optional[int] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Prediction:
        """
        Update prediction data by prediction ID.

        Parameters
        ----------
        id : int
            Prediction ID

        model_version : typing.Optional[str]
            Model version - tag for predictions that can be used to filter tasks in Data Manager, as well as select specific model version for showing preannotations in the labeling interface

        result : typing.Optional[typing.Sequence[typing.Dict[str, typing.Optional[typing.Any]]]]
            Prediction result in JSON format. Read more about the format in [the Label Studio documentation.](https://labelstud.io/guide/predictions)

        score : typing.Optional[float]
            Prediction score. Can be used in Data Manager to sort task by model confidence. Task with the lowest score will be shown first.

        task : typing.Optional[int]
            Task ID for which the prediction is created

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

        Returns
        -------
        Prediction
            Updated prediction

        Examples
        --------
        import asyncio

        from label_studio_sdk import AsyncLabelStudio

        client = AsyncLabelStudio(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.predictions.update(
                id=1,
                model_version="yolo-v8",
                result=[
                    {
                        "from_name": "bboxes",
                        "image_rotation": 0,
                        "original_height": 1080,
                        "original_width": 1920,
                        "to_name": "image",
                        "type": "rectanglelabels",
                        "value": {
                            "height": 60,
                            "rotation": 0,
                            "values": {"rectanglelabels": ["Person"]},
                            "width": 50,
                            "x": 20,
                            "y": 30,
                        },
                    }
                ],
                score=0.95,
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/predictions/{jsonable_encoder(id)}/",
            method="PATCH",
            json={
                "model_version": model_version,
                "result": result,
                "score": score,
                "task": task,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Prediction,
                    construct_type(
                        type_=Prediction,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)
