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

import typing
from ...core.client_wrapper import SyncClientWrapper
from .types.assignments_bulk_assign_request_selected_items import AssignmentsBulkAssignRequestSelectedItems
from .types.assignments_bulk_assign_request_type import AssignmentsBulkAssignRequestType
from .types.assignments_bulk_assign_request_filters import AssignmentsBulkAssignRequestFilters
from ...core.request_options import RequestOptions
from .types.assignments_bulk_assign_response import AssignmentsBulkAssignResponse
from ...core.jsonable_encoder import jsonable_encoder
from ...core.serialization import convert_and_respect_annotation_metadata
from ...core.unchecked_base_model import construct_type
from ...errors.bad_request_error import BadRequestError
from json.decoder import JSONDecodeError
from ...core.api_error import ApiError
from ...types.task_assignment import TaskAssignment
from .types.assignments_assign_request_type import AssignmentsAssignRequestType
from .types.assignments_delete_request_type import AssignmentsDeleteRequestType
from .types.assignments_update_request_type import AssignmentsUpdateRequestType
from ...core.client_wrapper import AsyncClientWrapper

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


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

    def bulk_assign(
        self,
        id: int,
        *,
        selected_items: AssignmentsBulkAssignRequestSelectedItems,
        type: AssignmentsBulkAssignRequestType,
        users: typing.Sequence[int],
        filters: typing.Optional[AssignmentsBulkAssignRequestFilters] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AssignmentsBulkAssignResponse:
        """
        Assign multiple users to a collection of tasks within a specific project.

        Parameters
        ----------
        id : int

        selected_items : AssignmentsBulkAssignRequestSelectedItems
            Task selection by IDs. If filters are applied, the selection will be applied to the filtered tasks.If "all" is `false`, `"included"` must be used. If "all" is `true`, `"excluded"` must be used.<br>Examples: `{"all": false, "included": [1, 2, 3]}` or `{"all": true, "excluded": [4, 5]}`

        type : AssignmentsBulkAssignRequestType
            Assignment type. Use AN for annotate or RE for review.

        users : typing.Sequence[int]
            List of user IDs to assign

        filters : typing.Optional[AssignmentsBulkAssignRequestFilters]
            Filters to apply on tasks. You can use [the helper class `Filters` from this page](https://labelstud.io/sdk/data_manager.html) to create Data Manager Filters.<br>Example: `{"conjunction": "or", "items": [{"filter": "filter:tasks:completed_at", "operator": "greater", "type": "Datetime", "value": "2021-01-01T00:00:00.000Z"}]}`

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

        Returns
        -------
        AssignmentsBulkAssignResponse
            Success

        Examples
        --------
        from label_studio_sdk import LabelStudio
        from label_studio_sdk.projects.assignments import (
            AssignmentsBulkAssignRequestSelectedItemsIncluded,
        )

        client = LabelStudio(
            api_key="YOUR_API_KEY",
        )
        client.projects.assignments.bulk_assign(
            id=1,
            selected_items=AssignmentsBulkAssignRequestSelectedItemsIncluded(
                all_=True,
            ),
            type="AN",
            users=[1],
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/projects/{jsonable_encoder(id)}/tasks/assignees",
            method="POST",
            json={
                "filters": convert_and_respect_annotation_metadata(
                    object_=filters, annotation=AssignmentsBulkAssignRequestFilters, direction="write"
                ),
                "selectedItems": convert_and_respect_annotation_metadata(
                    object_=selected_items, annotation=AssignmentsBulkAssignRequestSelectedItems, direction="write"
                ),
                "type": type,
                "users": users,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    AssignmentsBulkAssignResponse,
                    construct_type(
                        type_=AssignmentsBulkAssignResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        construct_type(
                            type_=typing.Optional[typing.Any],  # 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 list(
        self, id: int, task_pk: int, *, request_options: typing.Optional[RequestOptions] = None
    ) -> typing.List[TaskAssignment]:
        """
        Retrieve a list of tasks and assignees for those tasks for a specific project.

        Parameters
        ----------
        id : int
            A unique integer value identifying this project.

        task_pk : int
            A unique integer value identifying this task.

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

        Returns
        -------
        typing.List[TaskAssignment]
            List of assignments for the task

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

        client = LabelStudio(
            api_key="YOUR_API_KEY",
        )
        client.projects.assignments.list(
            id=1,
            task_pk=1,
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/projects/{jsonable_encoder(id)}/tasks/{jsonable_encoder(task_pk)}/assignees",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    typing.List[TaskAssignment],
                    construct_type(
                        type_=typing.List[TaskAssignment],  # 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 assign(
        self,
        id: int,
        task_pk: int,
        *,
        type: AssignmentsAssignRequestType,
        users: typing.Sequence[int],
        request_options: typing.Optional[RequestOptions] = None,
    ) -> TaskAssignment:
        """
        Assign a user to a task in a specific project.

        Parameters
        ----------
        id : int
            A unique integer value identifying this project.

        task_pk : int
            A unique integer value identifying this task.

        type : AssignmentsAssignRequestType
            Assignment type. Use AN for annotate or RE for review.

        users : typing.Sequence[int]
            List of user IDs to assign

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

        Returns
        -------
        TaskAssignment


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

        client = LabelStudio(
            api_key="YOUR_API_KEY",
        )
        client.projects.assignments.assign(
            id=1,
            task_pk=1,
            type="AN",
            users=[1],
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/projects/{jsonable_encoder(id)}/tasks/{jsonable_encoder(task_pk)}/assignees",
            method="POST",
            json={
                "type": type,
                "users": users,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    TaskAssignment,
                    construct_type(
                        type_=TaskAssignment,  # 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,
        task_pk: int,
        *,
        type: typing.Optional[AssignmentsDeleteRequestType] = None,
        users: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> None:
        """
        Remove assignees for a task within a specific project.

        Parameters
        ----------
        id : int
            A unique integer value identifying this project.

        task_pk : int
            A unique integer value identifying this task.

        type : typing.Optional[AssignmentsDeleteRequestType]
            Assignment type to delete (optional). If omitted, deletes all assignments for the task.

        users : typing.Optional[str]
            Comma separated list of user IDs to delete, as a string. If omitted, deletes all assignees for the given type.

        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.projects.assignments.delete(
            id=1,
            task_pk=1,
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/projects/{jsonable_encoder(id)}/tasks/{jsonable_encoder(task_pk)}/assignees",
            method="DELETE",
            params={
                "type": type,
                "users": users,
            },
            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,
        task_pk: int,
        *,
        type: AssignmentsUpdateRequestType,
        users: typing.Sequence[int],
        request_options: typing.Optional[RequestOptions] = None,
    ) -> TaskAssignment:
        """
        Update the assignee for a task in a specific project.

        Parameters
        ----------
        id : int
            A unique integer value identifying this project.

        task_pk : int
            A unique integer value identifying this task.

        type : AssignmentsUpdateRequestType
            Assignment type. Use AN for annotate or RE for review.

        users : typing.Sequence[int]
            List of user IDs to assign

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

        Returns
        -------
        TaskAssignment


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

        client = LabelStudio(
            api_key="YOUR_API_KEY",
        )
        client.projects.assignments.update(
            id=1,
            task_pk=1,
            type="AN",
            users=[1],
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/projects/{jsonable_encoder(id)}/tasks/{jsonable_encoder(task_pk)}/assignees",
            method="PATCH",
            json={
                "type": type,
                "users": users,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    TaskAssignment,
                    construct_type(
                        type_=TaskAssignment,  # 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 AsyncAssignmentsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def bulk_assign(
        self,
        id: int,
        *,
        selected_items: AssignmentsBulkAssignRequestSelectedItems,
        type: AssignmentsBulkAssignRequestType,
        users: typing.Sequence[int],
        filters: typing.Optional[AssignmentsBulkAssignRequestFilters] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AssignmentsBulkAssignResponse:
        """
        Assign multiple users to a collection of tasks within a specific project.

        Parameters
        ----------
        id : int

        selected_items : AssignmentsBulkAssignRequestSelectedItems
            Task selection by IDs. If filters are applied, the selection will be applied to the filtered tasks.If "all" is `false`, `"included"` must be used. If "all" is `true`, `"excluded"` must be used.<br>Examples: `{"all": false, "included": [1, 2, 3]}` or `{"all": true, "excluded": [4, 5]}`

        type : AssignmentsBulkAssignRequestType
            Assignment type. Use AN for annotate or RE for review.

        users : typing.Sequence[int]
            List of user IDs to assign

        filters : typing.Optional[AssignmentsBulkAssignRequestFilters]
            Filters to apply on tasks. You can use [the helper class `Filters` from this page](https://labelstud.io/sdk/data_manager.html) to create Data Manager Filters.<br>Example: `{"conjunction": "or", "items": [{"filter": "filter:tasks:completed_at", "operator": "greater", "type": "Datetime", "value": "2021-01-01T00:00:00.000Z"}]}`

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

        Returns
        -------
        AssignmentsBulkAssignResponse
            Success

        Examples
        --------
        import asyncio

        from label_studio_sdk import AsyncLabelStudio
        from label_studio_sdk.projects.assignments import (
            AssignmentsBulkAssignRequestSelectedItemsIncluded,
        )

        client = AsyncLabelStudio(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.projects.assignments.bulk_assign(
                id=1,
                selected_items=AssignmentsBulkAssignRequestSelectedItemsIncluded(
                    all_=True,
                ),
                type="AN",
                users=[1],
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/projects/{jsonable_encoder(id)}/tasks/assignees",
            method="POST",
            json={
                "filters": convert_and_respect_annotation_metadata(
                    object_=filters, annotation=AssignmentsBulkAssignRequestFilters, direction="write"
                ),
                "selectedItems": convert_and_respect_annotation_metadata(
                    object_=selected_items, annotation=AssignmentsBulkAssignRequestSelectedItems, direction="write"
                ),
                "type": type,
                "users": users,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    AssignmentsBulkAssignResponse,
                    construct_type(
                        type_=AssignmentsBulkAssignResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        construct_type(
                            type_=typing.Optional[typing.Any],  # 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 list(
        self, id: int, task_pk: int, *, request_options: typing.Optional[RequestOptions] = None
    ) -> typing.List[TaskAssignment]:
        """
        Retrieve a list of tasks and assignees for those tasks for a specific project.

        Parameters
        ----------
        id : int
            A unique integer value identifying this project.

        task_pk : int
            A unique integer value identifying this task.

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

        Returns
        -------
        typing.List[TaskAssignment]
            List of assignments for the task

        Examples
        --------
        import asyncio

        from label_studio_sdk import AsyncLabelStudio

        client = AsyncLabelStudio(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.projects.assignments.list(
                id=1,
                task_pk=1,
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/projects/{jsonable_encoder(id)}/tasks/{jsonable_encoder(task_pk)}/assignees",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    typing.List[TaskAssignment],
                    construct_type(
                        type_=typing.List[TaskAssignment],  # 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 assign(
        self,
        id: int,
        task_pk: int,
        *,
        type: AssignmentsAssignRequestType,
        users: typing.Sequence[int],
        request_options: typing.Optional[RequestOptions] = None,
    ) -> TaskAssignment:
        """
        Assign a user to a task in a specific project.

        Parameters
        ----------
        id : int
            A unique integer value identifying this project.

        task_pk : int
            A unique integer value identifying this task.

        type : AssignmentsAssignRequestType
            Assignment type. Use AN for annotate or RE for review.

        users : typing.Sequence[int]
            List of user IDs to assign

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

        Returns
        -------
        TaskAssignment


        Examples
        --------
        import asyncio

        from label_studio_sdk import AsyncLabelStudio

        client = AsyncLabelStudio(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.projects.assignments.assign(
                id=1,
                task_pk=1,
                type="AN",
                users=[1],
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/projects/{jsonable_encoder(id)}/tasks/{jsonable_encoder(task_pk)}/assignees",
            method="POST",
            json={
                "type": type,
                "users": users,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    TaskAssignment,
                    construct_type(
                        type_=TaskAssignment,  # 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,
        task_pk: int,
        *,
        type: typing.Optional[AssignmentsDeleteRequestType] = None,
        users: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> None:
        """
        Remove assignees for a task within a specific project.

        Parameters
        ----------
        id : int
            A unique integer value identifying this project.

        task_pk : int
            A unique integer value identifying this task.

        type : typing.Optional[AssignmentsDeleteRequestType]
            Assignment type to delete (optional). If omitted, deletes all assignments for the task.

        users : typing.Optional[str]
            Comma separated list of user IDs to delete, as a string. If omitted, deletes all assignees for the given type.

        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.projects.assignments.delete(
                id=1,
                task_pk=1,
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/projects/{jsonable_encoder(id)}/tasks/{jsonable_encoder(task_pk)}/assignees",
            method="DELETE",
            params={
                "type": type,
                "users": users,
            },
            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,
        task_pk: int,
        *,
        type: AssignmentsUpdateRequestType,
        users: typing.Sequence[int],
        request_options: typing.Optional[RequestOptions] = None,
    ) -> TaskAssignment:
        """
        Update the assignee for a task in a specific project.

        Parameters
        ----------
        id : int
            A unique integer value identifying this project.

        task_pk : int
            A unique integer value identifying this task.

        type : AssignmentsUpdateRequestType
            Assignment type. Use AN for annotate or RE for review.

        users : typing.Sequence[int]
            List of user IDs to assign

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

        Returns
        -------
        TaskAssignment


        Examples
        --------
        import asyncio

        from label_studio_sdk import AsyncLabelStudio

        client = AsyncLabelStudio(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.projects.assignments.update(
                id=1,
                task_pk=1,
                type="AN",
                users=[1],
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/projects/{jsonable_encoder(id)}/tasks/{jsonable_encoder(task_pk)}/assignees",
            method="PATCH",
            json={
                "type": type,
                "users": users,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    TaskAssignment,
                    construct_type(
                        type_=TaskAssignment,  # 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)
