# pylint: disable=too-many-lines
# 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.
# --------------------------------------------------------------------------
import json
import sys
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload

from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
    ClientAuthenticationError,
    HttpResponseError,
    ResourceExistsError,
    ResourceNotFoundError,
    ResourceNotModifiedError,
    map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict

from ... import models as _models
from ..._model_base import AzureJSONEncoder, _deserialize
from ..._operations._operations import (
    build_anomaly_detector_delete_multivariate_model_request,
    build_anomaly_detector_detect_multivariate_batch_anomaly_request,
    build_anomaly_detector_detect_multivariate_last_anomaly_request,
    build_anomaly_detector_detect_univariate_change_point_request,
    build_anomaly_detector_detect_univariate_entire_series_request,
    build_anomaly_detector_detect_univariate_last_point_request,
    build_anomaly_detector_get_multivariate_batch_detection_result_request,
    build_anomaly_detector_get_multivariate_model_request,
    build_anomaly_detector_list_multivariate_models_request,
    build_anomaly_detector_train_multivariate_model_request,
)
from .._vendor import AnomalyDetectorClientMixinABC

if sys.version_info >= (3, 9):
    from collections.abc import MutableMapping
else:
    from typing import MutableMapping  # type: ignore  # pylint: disable=ungrouped-imports
JSON = MutableMapping[str, Any]  # pylint: disable=unsubscriptable-object
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]


class AnomalyDetectorClientOperationsMixin(AnomalyDetectorClientMixinABC):
    @overload
    async def detect_univariate_entire_series(
        self, options: _models.UnivariateDetectionOptions, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.UnivariateEntireDetectionResult:
        """Detect anomalies for the entire series in batch.

        This operation generates a model with an entire series, each point is detected
        with the same model. With this method, points before and after a certain point
        are used to determine whether it is an anomaly. The entire detection can give
        user an overall status of the time series.

        :param options: Method of univariate anomaly detection. Required.
        :type options: ~anomalydetector.models.UnivariateDetectionOptions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: UnivariateEntireDetectionResult. The UnivariateEntireDetectionResult is compatible
         with MutableMapping
        :rtype: ~anomalydetector.models.UnivariateEntireDetectionResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def detect_univariate_entire_series(
        self, options: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.UnivariateEntireDetectionResult:
        """Detect anomalies for the entire series in batch.

        This operation generates a model with an entire series, each point is detected
        with the same model. With this method, points before and after a certain point
        are used to determine whether it is an anomaly. The entire detection can give
        user an overall status of the time series.

        :param options: Method of univariate anomaly detection. Required.
        :type options: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: UnivariateEntireDetectionResult. The UnivariateEntireDetectionResult is compatible
         with MutableMapping
        :rtype: ~anomalydetector.models.UnivariateEntireDetectionResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def detect_univariate_entire_series(
        self, options: IO, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.UnivariateEntireDetectionResult:
        """Detect anomalies for the entire series in batch.

        This operation generates a model with an entire series, each point is detected
        with the same model. With this method, points before and after a certain point
        are used to determine whether it is an anomaly. The entire detection can give
        user an overall status of the time series.

        :param options: Method of univariate anomaly detection. Required.
        :type options: IO
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: UnivariateEntireDetectionResult. The UnivariateEntireDetectionResult is compatible
         with MutableMapping
        :rtype: ~anomalydetector.models.UnivariateEntireDetectionResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def detect_univariate_entire_series(
        self, options: Union[_models.UnivariateDetectionOptions, JSON, IO], **kwargs: Any
    ) -> _models.UnivariateEntireDetectionResult:
        """Detect anomalies for the entire series in batch.

        This operation generates a model with an entire series, each point is detected
        with the same model. With this method, points before and after a certain point
        are used to determine whether it is an anomaly. The entire detection can give
        user an overall status of the time series.

        :param options: Method of univariate anomaly detection. Is one of the following types: model,
         JSON, IO Required.
        :type options: ~anomalydetector.models.UnivariateDetectionOptions or JSON or IO
        :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default
         value is None.
        :paramtype content_type: str
        :return: UnivariateEntireDetectionResult. The UnivariateEntireDetectionResult is compatible
         with MutableMapping
        :rtype: ~anomalydetector.models.UnivariateEntireDetectionResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map = {
            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.UnivariateEntireDetectionResult] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(options, (IO, bytes)):
            _content = options
        else:
            _content = json.dumps(options, cls=AzureJSONEncoder)

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

        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request, stream=False, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _deserialize(_models.AnomalyDetectorError, response.json())
            raise HttpResponseError(response=response, model=error)

        deserialized = _deserialize(_models.UnivariateEntireDetectionResult, response.json())

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

        return deserialized  # type: ignore

    @overload
    async def detect_univariate_last_point(
        self, options: _models.UnivariateDetectionOptions, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.UnivariateLastDetectionResult:
        """Detect anomaly status of the latest point in time series.

        This operation generates a model using the points that you sent into the API,
        and based on all data to determine whether the last point is anomalous.

        :param options: Method of univariate anomaly detection. Required.
        :type options: ~anomalydetector.models.UnivariateDetectionOptions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: UnivariateLastDetectionResult. The UnivariateLastDetectionResult is compatible with
         MutableMapping
        :rtype: ~anomalydetector.models.UnivariateLastDetectionResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def detect_univariate_last_point(
        self, options: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.UnivariateLastDetectionResult:
        """Detect anomaly status of the latest point in time series.

        This operation generates a model using the points that you sent into the API,
        and based on all data to determine whether the last point is anomalous.

        :param options: Method of univariate anomaly detection. Required.
        :type options: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: UnivariateLastDetectionResult. The UnivariateLastDetectionResult is compatible with
         MutableMapping
        :rtype: ~anomalydetector.models.UnivariateLastDetectionResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def detect_univariate_last_point(
        self, options: IO, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.UnivariateLastDetectionResult:
        """Detect anomaly status of the latest point in time series.

        This operation generates a model using the points that you sent into the API,
        and based on all data to determine whether the last point is anomalous.

        :param options: Method of univariate anomaly detection. Required.
        :type options: IO
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: UnivariateLastDetectionResult. The UnivariateLastDetectionResult is compatible with
         MutableMapping
        :rtype: ~anomalydetector.models.UnivariateLastDetectionResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def detect_univariate_last_point(
        self, options: Union[_models.UnivariateDetectionOptions, JSON, IO], **kwargs: Any
    ) -> _models.UnivariateLastDetectionResult:
        """Detect anomaly status of the latest point in time series.

        This operation generates a model using the points that you sent into the API,
        and based on all data to determine whether the last point is anomalous.

        :param options: Method of univariate anomaly detection. Is one of the following types: model,
         JSON, IO Required.
        :type options: ~anomalydetector.models.UnivariateDetectionOptions or JSON or IO
        :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default
         value is None.
        :paramtype content_type: str
        :return: UnivariateLastDetectionResult. The UnivariateLastDetectionResult is compatible with
         MutableMapping
        :rtype: ~anomalydetector.models.UnivariateLastDetectionResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map = {
            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.UnivariateLastDetectionResult] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(options, (IO, bytes)):
            _content = options
        else:
            _content = json.dumps(options, cls=AzureJSONEncoder)

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

        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request, stream=False, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _deserialize(_models.AnomalyDetectorError, response.json())
            raise HttpResponseError(response=response, model=error)

        deserialized = _deserialize(_models.UnivariateLastDetectionResult, response.json())

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

        return deserialized  # type: ignore

    @overload
    async def detect_univariate_change_point(
        self,
        options: _models.UnivariateChangePointDetectionOptions,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.UnivariateChangePointDetectionResult:
        """Detect change point for the entire series.

        Evaluate change point score of every series point.

        :param options: Method of univariate anomaly detection. Required.
        :type options: ~anomalydetector.models.UnivariateChangePointDetectionOptions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: UnivariateChangePointDetectionResult. The UnivariateChangePointDetectionResult is
         compatible with MutableMapping
        :rtype: ~anomalydetector.models.UnivariateChangePointDetectionResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def detect_univariate_change_point(
        self, options: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.UnivariateChangePointDetectionResult:
        """Detect change point for the entire series.

        Evaluate change point score of every series point.

        :param options: Method of univariate anomaly detection. Required.
        :type options: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: UnivariateChangePointDetectionResult. The UnivariateChangePointDetectionResult is
         compatible with MutableMapping
        :rtype: ~anomalydetector.models.UnivariateChangePointDetectionResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def detect_univariate_change_point(
        self, options: IO, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.UnivariateChangePointDetectionResult:
        """Detect change point for the entire series.

        Evaluate change point score of every series point.

        :param options: Method of univariate anomaly detection. Required.
        :type options: IO
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: UnivariateChangePointDetectionResult. The UnivariateChangePointDetectionResult is
         compatible with MutableMapping
        :rtype: ~anomalydetector.models.UnivariateChangePointDetectionResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def detect_univariate_change_point(
        self, options: Union[_models.UnivariateChangePointDetectionOptions, JSON, IO], **kwargs: Any
    ) -> _models.UnivariateChangePointDetectionResult:
        """Detect change point for the entire series.

        Evaluate change point score of every series point.

        :param options: Method of univariate anomaly detection. Is one of the following types: model,
         JSON, IO Required.
        :type options: ~anomalydetector.models.UnivariateChangePointDetectionOptions or JSON or IO
        :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default
         value is None.
        :paramtype content_type: str
        :return: UnivariateChangePointDetectionResult. The UnivariateChangePointDetectionResult is
         compatible with MutableMapping
        :rtype: ~anomalydetector.models.UnivariateChangePointDetectionResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map = {
            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.UnivariateChangePointDetectionResult] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(options, (IO, bytes)):
            _content = options
        else:
            _content = json.dumps(options, cls=AzureJSONEncoder)

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

        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request, stream=False, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _deserialize(_models.AnomalyDetectorError, response.json())
            raise HttpResponseError(response=response, model=error)

        deserialized = _deserialize(_models.UnivariateChangePointDetectionResult, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_multivariate_batch_detection_result(
        self, result_id: str, **kwargs: Any
    ) -> _models.MultivariateDetectionResult:
        """Get Multivariate Anomaly Detection Result.

        For asynchronous inference, get multivariate anomaly detection result based on
        resultId returned by the BatchDetectAnomaly api.

        :param result_id: ID of a batch detection result. Required.
        :type result_id: str
        :return: MultivariateDetectionResult. The MultivariateDetectionResult is compatible with
         MutableMapping
        :rtype: ~anomalydetector.models.MultivariateDetectionResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map = {
            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.MultivariateDetectionResult] = kwargs.pop("cls", None)

        request = build_anomaly_detector_get_multivariate_batch_detection_result_request(
            result_id=result_id,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
            "ApiVersion": self._serialize.url(
                "self._config.api_version", self._config.api_version, "str", skip_quote=True
            ),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)

        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request, stream=False, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _deserialize(_models.ResponseError, response.json())
            raise HttpResponseError(response=response, model=error)

        deserialized = _deserialize(_models.MultivariateDetectionResult, response.json())

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

        return deserialized  # type: ignore

    @overload
    async def train_multivariate_model(
        self, model_info: _models.ModelInfo, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.AnomalyDetectionModel:
        """Train a Multivariate Anomaly Detection Model.

        Create and train a multivariate anomaly detection model. The request must
        include a source parameter to indicate an externally accessible Azure blob
        storage URI.There are two types of data input: An URI pointed to an Azure blob
        storage folder which contains multiple CSV files, and each CSV file contains
        two columns, timestamp and variable. Another type of input is an URI pointed to
        a CSV file in Azure blob storage, which contains all the variables and a
        timestamp column.

        :param model_info: Model information. Required.
        :type model_info: ~anomalydetector.models.ModelInfo
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: AnomalyDetectionModel. The AnomalyDetectionModel is compatible with MutableMapping
        :rtype: ~anomalydetector.models.AnomalyDetectionModel
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def train_multivariate_model(
        self, model_info: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.AnomalyDetectionModel:
        """Train a Multivariate Anomaly Detection Model.

        Create and train a multivariate anomaly detection model. The request must
        include a source parameter to indicate an externally accessible Azure blob
        storage URI.There are two types of data input: An URI pointed to an Azure blob
        storage folder which contains multiple CSV files, and each CSV file contains
        two columns, timestamp and variable. Another type of input is an URI pointed to
        a CSV file in Azure blob storage, which contains all the variables and a
        timestamp column.

        :param model_info: Model information. Required.
        :type model_info: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: AnomalyDetectionModel. The AnomalyDetectionModel is compatible with MutableMapping
        :rtype: ~anomalydetector.models.AnomalyDetectionModel
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def train_multivariate_model(
        self, model_info: IO, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.AnomalyDetectionModel:
        """Train a Multivariate Anomaly Detection Model.

        Create and train a multivariate anomaly detection model. The request must
        include a source parameter to indicate an externally accessible Azure blob
        storage URI.There are two types of data input: An URI pointed to an Azure blob
        storage folder which contains multiple CSV files, and each CSV file contains
        two columns, timestamp and variable. Another type of input is an URI pointed to
        a CSV file in Azure blob storage, which contains all the variables and a
        timestamp column.

        :param model_info: Model information. Required.
        :type model_info: IO
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: AnomalyDetectionModel. The AnomalyDetectionModel is compatible with MutableMapping
        :rtype: ~anomalydetector.models.AnomalyDetectionModel
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def train_multivariate_model(
        self, model_info: Union[_models.ModelInfo, JSON, IO], **kwargs: Any
    ) -> _models.AnomalyDetectionModel:
        """Train a Multivariate Anomaly Detection Model.

        Create and train a multivariate anomaly detection model. The request must
        include a source parameter to indicate an externally accessible Azure blob
        storage URI.There are two types of data input: An URI pointed to an Azure blob
        storage folder which contains multiple CSV files, and each CSV file contains
        two columns, timestamp and variable. Another type of input is an URI pointed to
        a CSV file in Azure blob storage, which contains all the variables and a
        timestamp column.

        :param model_info: Model information. Is one of the following types: model, JSON, IO Required.
        :type model_info: ~anomalydetector.models.ModelInfo or JSON or IO
        :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default
         value is None.
        :paramtype content_type: str
        :return: AnomalyDetectionModel. The AnomalyDetectionModel is compatible with MutableMapping
        :rtype: ~anomalydetector.models.AnomalyDetectionModel
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map = {
            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.AnomalyDetectionModel] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(model_info, (IO, bytes)):
            _content = model_info
        else:
            _content = json.dumps(model_info, cls=AzureJSONEncoder)

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

        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request, stream=False, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [201]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _deserialize(_models.ResponseError, response.json())
            raise HttpResponseError(response=response, model=error)

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

        deserialized = _deserialize(_models.AnomalyDetectionModel, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace
    def list_multivariate_models(
        self, *, skip: Optional[int] = None, top: Optional[int] = None, **kwargs: Any
    ) -> AsyncIterable["_models.AnomalyDetectionModel"]:
        """List Multivariate Models.

        List models of a resource.

        :keyword skip: Skip indicates how many models will be skipped. Default value is None.
        :paramtype skip: int
        :keyword top: Top indicates how many models will be fetched. Default value is None.
        :paramtype top: int
        :return: An iterator like instance of AnomalyDetectionModel. The AnomalyDetectionModel is
         compatible with MutableMapping
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~anomalydetector.models.AnomalyDetectionModel]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models._models.ModelList] = kwargs.pop("cls", None)  # pylint: disable=protected-access

        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

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

            else:
                request = HttpRequest("GET", next_link)
                path_format_arguments = {
                    "Endpoint": self._serialize.url(
                        "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
                    ),
                    "ApiVersion": self._serialize.url(
                        "self._config.api_version", self._config.api_version, "str", skip_quote=True
                    ),
                }
                request.url = self._client.format_url(request.url, **path_format_arguments)

            return request

        async def extract_data(pipeline_response):
            deserialized = _deserialize(_models._models.ModelList, pipeline_response)
            list_of_elem = deserialized.models
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.next_link or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            request = prepare_request(next_link)

            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
                request, stream=False, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _deserialize(_models.ResponseError, response.json())
                raise HttpResponseError(response=response, model=error)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def delete_multivariate_model(  # pylint: disable=inconsistent-return-statements
        self, model_id: str, **kwargs: Any
    ) -> None:
        """Delete Multivariate Model.

        Delete an existing multivariate model according to the modelId.

        :param model_id: Model identifier. Required.
        :type model_id: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map = {
            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[None] = kwargs.pop("cls", None)

        request = build_anomaly_detector_delete_multivariate_model_request(
            model_id=model_id,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
            "ApiVersion": self._serialize.url(
                "self._config.api_version", self._config.api_version, "str", skip_quote=True
            ),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)

        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request, stream=False, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _deserialize(_models.ResponseError, response.json())
            raise HttpResponseError(response=response, model=error)

        if cls:
            return cls(pipeline_response, None, {})

    @distributed_trace_async
    async def get_multivariate_model(self, model_id: str, **kwargs: Any) -> _models.AnomalyDetectionModel:
        """Get Multivariate Model.

        Get detailed information of multivariate model, including the training status
        and variables used in the model.

        :param model_id: Model identifier. Required.
        :type model_id: str
        :return: AnomalyDetectionModel. The AnomalyDetectionModel is compatible with MutableMapping
        :rtype: ~anomalydetector.models.AnomalyDetectionModel
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map = {
            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.AnomalyDetectionModel] = kwargs.pop("cls", None)

        request = build_anomaly_detector_get_multivariate_model_request(
            model_id=model_id,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
            "ApiVersion": self._serialize.url(
                "self._config.api_version", self._config.api_version, "str", skip_quote=True
            ),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)

        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request, stream=False, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _deserialize(_models.ResponseError, response.json())
            raise HttpResponseError(response=response, model=error)

        deserialized = _deserialize(_models.AnomalyDetectionModel, response.json())

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

        return deserialized  # type: ignore

    @overload
    async def detect_multivariate_batch_anomaly(
        self,
        model_id: str,
        options: _models.MultivariateBatchDetectionOptions,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.MultivariateDetectionResult:
        """Detect Multivariate Anomaly.

        Submit multivariate anomaly detection task with the modelId of trained model
        and inference data, the input schema should be the same with the training
        request. The request will complete asynchronously and return a resultId to
        query the detection result.The request should be a source link to indicate an
        externally accessible Azure storage Uri, either pointed to an Azure blob
        storage folder, or pointed to a CSV file in Azure blob storage.

        :param model_id: Model identifier. Required.
        :type model_id: str
        :param options: Request of multivariate anomaly detection. Required.
        :type options: ~anomalydetector.models.MultivariateBatchDetectionOptions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: MultivariateDetectionResult. The MultivariateDetectionResult is compatible with
         MutableMapping
        :rtype: ~anomalydetector.models.MultivariateDetectionResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def detect_multivariate_batch_anomaly(
        self, model_id: str, options: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.MultivariateDetectionResult:
        """Detect Multivariate Anomaly.

        Submit multivariate anomaly detection task with the modelId of trained model
        and inference data, the input schema should be the same with the training
        request. The request will complete asynchronously and return a resultId to
        query the detection result.The request should be a source link to indicate an
        externally accessible Azure storage Uri, either pointed to an Azure blob
        storage folder, or pointed to a CSV file in Azure blob storage.

        :param model_id: Model identifier. Required.
        :type model_id: str
        :param options: Request of multivariate anomaly detection. Required.
        :type options: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: MultivariateDetectionResult. The MultivariateDetectionResult is compatible with
         MutableMapping
        :rtype: ~anomalydetector.models.MultivariateDetectionResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def detect_multivariate_batch_anomaly(
        self, model_id: str, options: IO, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.MultivariateDetectionResult:
        """Detect Multivariate Anomaly.

        Submit multivariate anomaly detection task with the modelId of trained model
        and inference data, the input schema should be the same with the training
        request. The request will complete asynchronously and return a resultId to
        query the detection result.The request should be a source link to indicate an
        externally accessible Azure storage Uri, either pointed to an Azure blob
        storage folder, or pointed to a CSV file in Azure blob storage.

        :param model_id: Model identifier. Required.
        :type model_id: str
        :param options: Request of multivariate anomaly detection. Required.
        :type options: IO
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: MultivariateDetectionResult. The MultivariateDetectionResult is compatible with
         MutableMapping
        :rtype: ~anomalydetector.models.MultivariateDetectionResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def detect_multivariate_batch_anomaly(
        self, model_id: str, options: Union[_models.MultivariateBatchDetectionOptions, JSON, IO], **kwargs: Any
    ) -> _models.MultivariateDetectionResult:
        """Detect Multivariate Anomaly.

        Submit multivariate anomaly detection task with the modelId of trained model
        and inference data, the input schema should be the same with the training
        request. The request will complete asynchronously and return a resultId to
        query the detection result.The request should be a source link to indicate an
        externally accessible Azure storage Uri, either pointed to an Azure blob
        storage folder, or pointed to a CSV file in Azure blob storage.

        :param model_id: Model identifier. Required.
        :type model_id: str
        :param options: Request of multivariate anomaly detection. Is one of the following types:
         model, JSON, IO Required.
        :type options: ~anomalydetector.models.MultivariateBatchDetectionOptions or JSON or IO
        :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default
         value is None.
        :paramtype content_type: str
        :return: MultivariateDetectionResult. The MultivariateDetectionResult is compatible with
         MutableMapping
        :rtype: ~anomalydetector.models.MultivariateDetectionResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map = {
            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.MultivariateDetectionResult] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(options, (IO, bytes)):
            _content = options
        else:
            _content = json.dumps(options, cls=AzureJSONEncoder)

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

        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request, stream=False, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [202]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _deserialize(_models.ResponseError, response.json())
            raise HttpResponseError(response=response, model=error)

        response_headers = {}
        response_headers["operation-id"] = self._deserialize("str", response.headers.get("operation-id"))
        response_headers["operation-location"] = self._deserialize("str", response.headers.get("operation-location"))

        deserialized = _deserialize(_models.MultivariateDetectionResult, response.json())

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

        return deserialized  # type: ignore

    @overload
    async def detect_multivariate_last_anomaly(
        self,
        model_id: str,
        options: _models.MultivariateLastDetectionOptions,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.MultivariateLastDetectionResult:
        """Detect anomalies in the last point of the request body.

        Submit multivariate anomaly detection task with the modelId of trained model
        and inference data, and the inference data should be put into request body in a
        JSON format. The request will complete synchronously and return the detection
        immediately in the response body.

        :param model_id: Model identifier. Required.
        :type model_id: str
        :param options: Request of last detection. Required.
        :type options: ~anomalydetector.models.MultivariateLastDetectionOptions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: MultivariateLastDetectionResult. The MultivariateLastDetectionResult is compatible
         with MutableMapping
        :rtype: ~anomalydetector.models.MultivariateLastDetectionResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def detect_multivariate_last_anomaly(
        self, model_id: str, options: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.MultivariateLastDetectionResult:
        """Detect anomalies in the last point of the request body.

        Submit multivariate anomaly detection task with the modelId of trained model
        and inference data, and the inference data should be put into request body in a
        JSON format. The request will complete synchronously and return the detection
        immediately in the response body.

        :param model_id: Model identifier. Required.
        :type model_id: str
        :param options: Request of last detection. Required.
        :type options: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: MultivariateLastDetectionResult. The MultivariateLastDetectionResult is compatible
         with MutableMapping
        :rtype: ~anomalydetector.models.MultivariateLastDetectionResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def detect_multivariate_last_anomaly(
        self, model_id: str, options: IO, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.MultivariateLastDetectionResult:
        """Detect anomalies in the last point of the request body.

        Submit multivariate anomaly detection task with the modelId of trained model
        and inference data, and the inference data should be put into request body in a
        JSON format. The request will complete synchronously and return the detection
        immediately in the response body.

        :param model_id: Model identifier. Required.
        :type model_id: str
        :param options: Request of last detection. Required.
        :type options: IO
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: MultivariateLastDetectionResult. The MultivariateLastDetectionResult is compatible
         with MutableMapping
        :rtype: ~anomalydetector.models.MultivariateLastDetectionResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def detect_multivariate_last_anomaly(
        self, model_id: str, options: Union[_models.MultivariateLastDetectionOptions, JSON, IO], **kwargs: Any
    ) -> _models.MultivariateLastDetectionResult:
        """Detect anomalies in the last point of the request body.

        Submit multivariate anomaly detection task with the modelId of trained model
        and inference data, and the inference data should be put into request body in a
        JSON format. The request will complete synchronously and return the detection
        immediately in the response body.

        :param model_id: Model identifier. Required.
        :type model_id: str
        :param options: Request of last detection. Is one of the following types: model, JSON, IO
         Required.
        :type options: ~anomalydetector.models.MultivariateLastDetectionOptions or JSON or IO
        :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default
         value is None.
        :paramtype content_type: str
        :return: MultivariateLastDetectionResult. The MultivariateLastDetectionResult is compatible
         with MutableMapping
        :rtype: ~anomalydetector.models.MultivariateLastDetectionResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map = {
            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.MultivariateLastDetectionResult] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(options, (IO, bytes)):
            _content = options
        else:
            _content = json.dumps(options, cls=AzureJSONEncoder)

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

        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request, stream=False, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _deserialize(_models.ResponseError, response.json())
            raise HttpResponseError(response=response, model=error)

        deserialized = _deserialize(_models.MultivariateLastDetectionResult, response.json())

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

        return deserialized  # type: ignore
