# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) Python Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from collections.abc import MutableMapping
from io import IOBase
import json
from typing import Any, Callable, IO, Iterator, Optional, TypeVar, Union, cast, overload

from azure.core import PipelineClient
from azure.core.exceptions import (
    ClientAuthenticationError,
    HttpResponseError,
    ResourceExistsError,
    ResourceNotFoundError,
    ResourceNotModifiedError,
    StreamClosedError,
    StreamConsumedError,
    map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.polling.base_polling import LROBasePolling
from azure.core.rest import HttpRequest, HttpResponse
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict

from .. import models as _models
from .._configuration import TextAnalysisClientConfiguration
from .._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize
from .._utils.serialization import Serializer
from .._utils.utils import ClientMixinABC

JSON = MutableMapping[str, Any]
_Unset: Any = object()
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]]

_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False


def build_text_analysis_analyze_text_request(*, show_stats: Optional[bool] = None, **kwargs: Any) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
    api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-15-preview"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = "/:analyze-text"

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
    if show_stats is not None:
        _params["showStats"] = _SERIALIZER.query("show_stats", show_stats, "bool")

    # Construct headers
    if content_type is not None:
        _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)


def build_text_analysis_get_job_status_request(  # pylint: disable=name-too-long
    job_id: str,
    *,
    show_stats: Optional[bool] = None,
    top: Optional[int] = None,
    skip: Optional[int] = None,
    **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-15-preview"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = "/analyze-text/jobs/{jobId}"
    path_format_arguments = {
        "jobId": _SERIALIZER.url("job_id", job_id, "str"),
    }

    _url: str = _url.format(**path_format_arguments)  # type: ignore

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
    if show_stats is not None:
        _params["showStats"] = _SERIALIZER.query("show_stats", show_stats, "bool")
    if top is not None:
        _params["top"] = _SERIALIZER.query("top", top, "int")
    if skip is not None:
        _params["skip"] = _SERIALIZER.query("skip", skip, "int")

    # Construct headers
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)


def build_text_analysis_analyze_text_job_request(**kwargs: Any) -> HttpRequest:  # pylint: disable=name-too-long
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
    api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-15-preview"))
    # Construct URL
    _url = "/analyze-text/jobs"

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    if content_type is not None:
        _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")

    return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)


def build_text_analysis_cancel_job_request(job_id: str, **kwargs: Any) -> HttpRequest:
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-11-15-preview"))
    # Construct URL
    _url = "/analyze-text/jobs/{jobId}:cancel"
    path_format_arguments = {
        "jobId": _SERIALIZER.url("job_id", job_id, "str"),
    }

    _url: str = _url.format(**path_format_arguments)  # type: ignore

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    return HttpRequest(method="POST", url=_url, params=_params, **kwargs)


class _TextAnalysisClientOperationsMixin(
    ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], TextAnalysisClientConfiguration]
):

    @overload
    def analyze_text(
        self,
        body: _models.AnalyzeTextInput,
        *,
        show_stats: Optional[bool] = None,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.AnalyzeTextResult:
        """Request text analysis over a collection of documents.

        :param body: The input documents to analyze. Required.
        :type body: ~azure.ai.textanalytics.models.AnalyzeTextInput
        :keyword show_stats: (Optional) if set to true, response will contain request and document
         level statistics. Default value is None.
        :paramtype show_stats: bool
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: AnalyzeTextResult. The AnalyzeTextResult is compatible with MutableMapping
        :rtype: ~azure.ai.textanalytics.models.AnalyzeTextResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    def analyze_text(
        self, body: JSON, *, show_stats: Optional[bool] = None, content_type: str = "application/json", **kwargs: Any
    ) -> _models.AnalyzeTextResult:
        """Request text analysis over a collection of documents.

        :param body: The input documents to analyze. Required.
        :type body: JSON
        :keyword show_stats: (Optional) if set to true, response will contain request and document
         level statistics. Default value is None.
        :paramtype show_stats: bool
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: AnalyzeTextResult. The AnalyzeTextResult is compatible with MutableMapping
        :rtype: ~azure.ai.textanalytics.models.AnalyzeTextResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    def analyze_text(
        self,
        body: IO[bytes],
        *,
        show_stats: Optional[bool] = None,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.AnalyzeTextResult:
        """Request text analysis over a collection of documents.

        :param body: The input documents to analyze. Required.
        :type body: IO[bytes]
        :keyword show_stats: (Optional) if set to true, response will contain request and document
         level statistics. Default value is None.
        :paramtype show_stats: bool
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: AnalyzeTextResult. The AnalyzeTextResult is compatible with MutableMapping
        :rtype: ~azure.ai.textanalytics.models.AnalyzeTextResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace
    def analyze_text(
        self,
        body: Union[_models.AnalyzeTextInput, JSON, IO[bytes]],
        *,
        show_stats: Optional[bool] = None,
        **kwargs: Any
    ) -> _models.AnalyzeTextResult:
        """Request text analysis over a collection of documents.

        :param body: The input documents to analyze. Is one of the following types: AnalyzeTextInput,
         JSON, IO[bytes] Required.
        :type body: ~azure.ai.textanalytics.models.AnalyzeTextInput or JSON or IO[bytes]
        :keyword show_stats: (Optional) if set to true, response will contain request and document
         level statistics. Default value is None.
        :paramtype show_stats: bool
        :return: AnalyzeTextResult. The AnalyzeTextResult is compatible with MutableMapping
        :rtype: ~azure.ai.textanalytics.models.AnalyzeTextResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.AnalyzeTextResult] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(body, (IOBase, bytes)):
            _content = body
        else:
            _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_text_analysis_analyze_text_request(
            show_stats=show_stats,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error)

        if _stream:
            deserialized = response.iter_bytes()
        else:
            deserialized = _deserialize(_models.AnalyzeTextResult, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def get_job_status(
        self,
        job_id: str,
        *,
        show_stats: Optional[bool] = None,
        top: Optional[int] = None,
        skip: Optional[int] = None,
        **kwargs: Any
    ) -> _models.AnalyzeTextOperationState:
        """Get analysis status and results.

        Get the status of an analysis job. A job can consist of one or more tasks. After all tasks
        succeed, the job transitions to the succeeded state and results are available for each task.

        :param job_id: job ID. Required.
        :type job_id: str
        :keyword show_stats: (Optional) if set to true, response will contain request and document
         level statistics. Default value is None.
        :paramtype show_stats: bool
        :keyword top: The maximum number of resources to return from the collection. Default value is
         None.
        :paramtype top: int
        :keyword skip: An offset into the collection of the first resource to be returned. Default
         value is None.
        :paramtype skip: int
        :return: AnalyzeTextOperationState. The AnalyzeTextOperationState is compatible with
         MutableMapping
        :rtype: ~azure.ai.textanalytics.models.AnalyzeTextOperationState
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.AnalyzeTextOperationState] = kwargs.pop("cls", None)

        _request = build_text_analysis_get_job_status_request(
            job_id=job_id,
            show_stats=show_stats,
            top=top,
            skip=skip,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error)

        if _stream:
            deserialized = response.iter_bytes()
        else:
            deserialized = _deserialize(_models.AnalyzeTextOperationState, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    def _analyze_text_job_initial(
        self,
        body: Union[JSON, IO[bytes]] = _Unset,
        *,
        text_input: _models.MultiLanguageTextInput = _Unset,
        actions: list[_models.AnalyzeTextOperationAction] = _Unset,
        display_name: Optional[str] = None,
        default_language: Optional[str] = None,
        cancel_after: Optional[float] = None,
        **kwargs: Any
    ) -> Iterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None)

        if body is _Unset:
            if text_input is _Unset:
                raise TypeError("missing required argument: text_input")
            if actions is _Unset:
                raise TypeError("missing required argument: actions")
            body = {
                "analysisInput": text_input,
                "cancelAfter": cancel_after,
                "defaultLanguage": default_language,
                "displayName": display_name,
                "tasks": actions,
            }
            body = {k: v for k, v in body.items() if v is not None}
        content_type = content_type or "application/json"
        _content = None
        if isinstance(body, (IOBase, bytes)):
            _content = body
        else:
            _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_text_analysis_analyze_text_job_request(
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = True
        pipeline_response: PipelineResponse = self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [202]:
            try:
                response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error)

        response_headers = {}
        response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location"))

        deserialized = response.iter_bytes()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    def begin_analyze_text_job(
        self,
        *,
        text_input: _models.MultiLanguageTextInput,
        actions: list[_models.AnalyzeTextOperationAction],
        content_type: str = "application/json",
        display_name: Optional[str] = None,
        default_language: Optional[str] = None,
        cancel_after: Optional[float] = None,
        **kwargs: Any
    ) -> LROPoller[None]:
        """Submit a collection of text documents for analysis. Specify one or more unique tasks to be
        executed as a long-running operation.

        :keyword text_input: Contains the input to be analyzed. Required.
        :paramtype text_input: ~azure.ai.textanalytics.models.MultiLanguageTextInput
        :keyword actions: List of tasks to be performed as part of the LRO. Required.
        :paramtype actions: list[~azure.ai.textanalytics.models.AnalyzeTextOperationAction]
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword display_name: Name for the task. Default value is None.
        :paramtype display_name: str
        :keyword default_language: Default language to use for records requesting automatic language
         detection. Default value is None.
        :paramtype default_language: str
        :keyword cancel_after: Optional duration in seconds after which the job will be canceled if not
         completed. Default value is None.
        :paramtype cancel_after: float
        :return: An instance of LROPoller that returns None
        :rtype: ~azure.core.polling.LROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    def begin_analyze_text_job(
        self, body: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> LROPoller[None]:
        """Submit a collection of text documents for analysis. Specify one or more unique tasks to be
        executed as a long-running operation.

        :param body: Required.
        :type body: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of LROPoller that returns None
        :rtype: ~azure.core.polling.LROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    def begin_analyze_text_job(
        self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> LROPoller[None]:
        """Submit a collection of text documents for analysis. Specify one or more unique tasks to be
        executed as a long-running operation.

        :param body: Required.
        :type body: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of LROPoller that returns None
        :rtype: ~azure.core.polling.LROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace
    def begin_analyze_text_job(
        self,
        body: Union[JSON, IO[bytes]] = _Unset,
        *,
        text_input: _models.MultiLanguageTextInput = _Unset,
        actions: list[_models.AnalyzeTextOperationAction] = _Unset,
        display_name: Optional[str] = None,
        default_language: Optional[str] = None,
        cancel_after: Optional[float] = None,
        **kwargs: Any
    ) -> LROPoller[None]:
        """Submit a collection of text documents for analysis. Specify one or more unique tasks to be
        executed as a long-running operation.

        :param body: Is either a JSON type or a IO[bytes] type. Required.
        :type body: JSON or IO[bytes]
        :keyword text_input: Contains the input to be analyzed. Required.
        :paramtype text_input: ~azure.ai.textanalytics.models.MultiLanguageTextInput
        :keyword actions: List of tasks to be performed as part of the LRO. Required.
        :paramtype actions: list[~azure.ai.textanalytics.models.AnalyzeTextOperationAction]
        :keyword display_name: Name for the task. Default value is None.
        :paramtype display_name: str
        :keyword default_language: Default language to use for records requesting automatic language
         detection. Default value is None.
        :paramtype default_language: str
        :keyword cancel_after: Optional duration in seconds after which the job will be canceled if not
         completed. Default value is None.
        :paramtype cancel_after: float
        :return: An instance of LROPoller that returns None
        :rtype: ~azure.core.polling.LROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[None] = kwargs.pop("cls", None)
        polling: Union[bool, PollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = self._analyze_text_job_initial(
                body=body,
                text_input=text_input,
                actions=actions,
                display_name=display_name,
                default_language=default_language,
                cancel_after=cancel_after,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):  # pylint: disable=inconsistent-return-statements
            if cls:
                return cls(pipeline_response, None, {})  # type: ignore

        path_format_arguments = {
            "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: PollingMethod = cast(
                PollingMethod, LROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(PollingMethod, NoPolling())
        else:
            polling_method = polling
        if cont_token:
            return LROPoller[None].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method)  # type: ignore

    def _cancel_job_initial(self, job_id: str, **kwargs: Any) -> Iterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None)

        _request = build_text_analysis_cancel_job_request(
            job_id=job_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = True
        pipeline_response: PipelineResponse = self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [202]:
            try:
                response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error)

        response_headers = {}
        response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location"))

        deserialized = response.iter_bytes()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def begin_cancel_job(self, job_id: str, **kwargs: Any) -> LROPoller[None]:
        """Cancel a long-running Text Analysis job.

        Cancel a long-running Text Analysis job.

        :param job_id: The job ID to cancel. Required.
        :type job_id: str
        :return: An instance of LROPoller that returns None
        :rtype: ~azure.core.polling.LROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)
        polling: Union[bool, PollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = self._cancel_job_initial(
                job_id=job_id, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs
            )
            raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):  # pylint: disable=inconsistent-return-statements
            if cls:
                return cls(pipeline_response, None, {})  # type: ignore

        path_format_arguments = {
            "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: PollingMethod = cast(
                PollingMethod, LROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(PollingMethod, NoPolling())
        else:
            polling_method = polling
        if cont_token:
            return LROPoller[None].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method)  # type: ignore
