# coding: utf-8

"""
Earnix Elevate Umon API

No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)

The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)

Do not edit the class manually.
"""


from datetime import datetime
from typing import Optional

from pydantic.v1 import Field, StrictStr, validate_arguments
from typing_extensions import Annotated

from earnix_elevate.clients.umon.api_client import ApiClient
from earnix_elevate.clients.umon.api_response import ApiResponse
from earnix_elevate.clients.umon.exceptions import ApiTypeError
from earnix_elevate.clients.umon.models.usage_monitoring_response import (
    UsageMonitoringResponse,
)


class UsageMonitoringServiceApi:
    """NOTE: This class is auto generated by OpenAPI Generator
    Ref: https://openapi-generator.tech

    Do not edit the class manually.
    """

    def __init__(self, api_client=None) -> None:
        if api_client is None:
            api_client = ApiClient.get_default()
        self.api_client = api_client

    @validate_arguments
    def download_usage_metrics_csv(
        self,
        metric_type: Annotated[
            StrictStr,
            Field(
                ...,
                description="Type of usage metric to aggregate. Supported types are DATA_TRANSFER_VOLUME_BYTES (total bytes transferred) and CPU_TIME_MS (total CPU time in milliseconds).",
            ),
        ],
        start_date: Annotated[
            Optional[datetime], Field(description="Start of date range")
        ] = None,
        end_date: Annotated[
            Optional[datetime], Field(description="End of date range")
        ] = None,
        **kwargs,
    ) -> bytearray:
        """Downloads detailed usage metrics as CSV stream. Returns all usage aggregation records matching the specified metric type and date range. The CSV includes all entity fields including tenant ID, job details, metric values, and metric-specific details in JSON format. Data is streamed in pages to support large downloads efficiently.

        :param metric_type: Type of usage metric to aggregate. Supported types are DATA_TRANSFER_VOLUME_BYTES (total bytes transferred) and CPU_TIME_MS (total CPU time in milliseconds). (required)
        :type metric_type: str
        :param start_date: Start of date range
        :type start_date: datetime
        :param end_date: End of date range
        :type end_date: datetime
        :return: Returns the result object.
        :rtype: bytearray
        """
        kwargs["_return_http_data_only"] = True
        if "_preload_content" in kwargs:
            message = "Error! Please call the download_usage_metrics_csv_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data"
            raise ValueError(message)
        return self.download_usage_metrics_csv_with_http_info(
            metric_type, start_date, end_date, **kwargs
        )

    @validate_arguments
    def download_usage_metrics_csv_with_http_info(
        self,
        metric_type: Annotated[
            StrictStr,
            Field(
                ...,
                description="Type of usage metric to aggregate. Supported types are DATA_TRANSFER_VOLUME_BYTES (total bytes transferred) and CPU_TIME_MS (total CPU time in milliseconds).",
            ),
        ],
        start_date: Annotated[
            Optional[datetime], Field(description="Start of date range")
        ] = None,
        end_date: Annotated[
            Optional[datetime], Field(description="End of date range")
        ] = None,
        **kwargs,
    ) -> ApiResponse:
        """Downloads detailed usage metrics as CSV stream. Returns all usage aggregation records matching the specified metric type and date range. The CSV includes all entity fields including tenant ID, job details, metric values, and metric-specific details in JSON format. Data is streamed in pages to support large downloads efficiently.

        :param metric_type: Type of usage metric to aggregate. Supported types are DATA_TRANSFER_VOLUME_BYTES (total bytes transferred) and CPU_TIME_MS (total CPU time in milliseconds). (required)
        :type metric_type: str
        :param start_date: Start of date range
        :type start_date: datetime
        :param end_date: End of date range
        :type end_date: datetime
        :param _preload_content: if False, the ApiResponse.data will
                                 be set to none and raw_data will store the
                                 HTTP response body without reading/decoding.
                                 Default is True.
        :type _preload_content: bool, optional
        :param _return_http_data_only: response data instead of ApiResponse
                                       object with status code, headers, etc
        :type _return_http_data_only: bool, optional
        :param _request_auth: set to override the auth_settings for an a single
                              request; this effectively ignores the authentication
                              in the spec for a single request.
        :type _request_auth: dict, optional
        :type _content_type: string, optional: force content-type for the request
        :return: Returns the result object.
        :rtype: tuple(bytearray, status_code(int), headers(HTTPHeaderDict))
        """

        _params = locals()

        _all_params = ["metric_type", "start_date", "end_date"]
        _all_params.extend(
            [
                "async_req",
                "_return_http_data_only",
                "_preload_content",
                "_request_timeout",
                "_request_auth",
                "_content_type",
                "_headers",
            ]
        )

        # validate the arguments
        for _key, _val in _params["kwargs"].items():
            if _key not in _all_params:
                raise ApiTypeError(
                    "Got an unexpected keyword argument '%s'"
                    " to method download_usage_metrics_csv" % _key
                )
            _params[_key] = _val
        del _params["kwargs"]

        _collection_formats = {}

        # process the path parameters
        _path_params = {}

        # process the query parameters
        _query_params = []
        if _params.get("metric_type") is not None:
            _query_params.append(("metricType", _params["metric_type"]))

        if _params.get("start_date") is not None:
            if isinstance(_params["start_date"], datetime):
                _query_params.append(
                    (
                        "startDate",
                        _params["start_date"].strftime(
                            self.api_client.configuration.datetime_format
                        ),
                    )
                )
            else:
                _query_params.append(("startDate", _params["start_date"]))

        if _params.get("end_date") is not None:
            if isinstance(_params["end_date"], datetime):
                _query_params.append(
                    (
                        "endDate",
                        _params["end_date"].strftime(
                            self.api_client.configuration.datetime_format
                        ),
                    )
                )
            else:
                _query_params.append(("endDate", _params["end_date"]))

        # process the header parameters
        _header_params = dict(_params.get("_headers", {}))
        # process the form parameters
        _form_params = []
        _files = {}
        # process the body parameter
        _body_params = None
        # set the HTTP header `Accept`
        _header_params["Accept"] = self.api_client.select_header_accept(
            ["text/csv", "application/problem+json"]
        )

        # authentication setting
        _auth_settings = ["BearerAuth"]

        _response_types_map = {
            "200": "bytearray",
        }

        return self.api_client.call_api(
            "/v1/usage-metrics/download",
            "GET",
            _path_params,
            _query_params,
            _header_params,
            body=_body_params,
            post_params=_form_params,
            files=_files,
            response_types_map=_response_types_map,
            auth_settings=_auth_settings,
            async_req=_params.get("async_req"),
            _return_http_data_only=_params.get("_return_http_data_only"),
            _preload_content=_params.get("_preload_content", True),
            _request_timeout=_params.get("_request_timeout"),
            collection_formats=_collection_formats,
            _request_auth=_params.get("_request_auth"),
        )

    @validate_arguments
    def get_usage_summary(
        self,
        metric_type: Annotated[
            StrictStr,
            Field(
                ...,
                description="Type of usage metric to aggregate. Supported types are DATA_TRANSFER_VOLUME_BYTES (total bytes transferred) and CPU_TIME_MS (total CPU time in milliseconds).",
            ),
        ],
        start_date: Annotated[
            Optional[datetime], Field(description="Start of date range")
        ] = None,
        end_date: Annotated[
            Optional[datetime], Field(description="End of date range")
        ] = None,
        **kwargs,
    ) -> UsageMonitoringResponse:
        """Retrieves aggregated usage metrics for the current tenant. This API requires the metricType query parameter (DATA_TRANSFER_VOLUME_BYTES or CPU_TIME_MS). Returns a UsageMonitoringResponse object containing metricType and totalValue fields, providing the total aggregated metric value across all jobs for monitoring resource consumption and usage patterns.

        :param metric_type: Type of usage metric to aggregate. Supported types are DATA_TRANSFER_VOLUME_BYTES (total bytes transferred) and CPU_TIME_MS (total CPU time in milliseconds). (required)
        :type metric_type: str
        :param start_date: Start of date range
        :type start_date: datetime
        :param end_date: End of date range
        :type end_date: datetime
        :return: Returns the result object.
        :rtype: UsageMonitoringResponse
        """
        kwargs["_return_http_data_only"] = True
        if "_preload_content" in kwargs:
            message = "Error! Please call the get_usage_summary_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data"
            raise ValueError(message)
        return self.get_usage_summary_with_http_info(
            metric_type, start_date, end_date, **kwargs
        )

    @validate_arguments
    def get_usage_summary_with_http_info(
        self,
        metric_type: Annotated[
            StrictStr,
            Field(
                ...,
                description="Type of usage metric to aggregate. Supported types are DATA_TRANSFER_VOLUME_BYTES (total bytes transferred) and CPU_TIME_MS (total CPU time in milliseconds).",
            ),
        ],
        start_date: Annotated[
            Optional[datetime], Field(description="Start of date range")
        ] = None,
        end_date: Annotated[
            Optional[datetime], Field(description="End of date range")
        ] = None,
        **kwargs,
    ) -> ApiResponse:
        """Retrieves aggregated usage metrics for the current tenant. This API requires the metricType query parameter (DATA_TRANSFER_VOLUME_BYTES or CPU_TIME_MS). Returns a UsageMonitoringResponse object containing metricType and totalValue fields, providing the total aggregated metric value across all jobs for monitoring resource consumption and usage patterns.

        :param metric_type: Type of usage metric to aggregate. Supported types are DATA_TRANSFER_VOLUME_BYTES (total bytes transferred) and CPU_TIME_MS (total CPU time in milliseconds). (required)
        :type metric_type: str
        :param start_date: Start of date range
        :type start_date: datetime
        :param end_date: End of date range
        :type end_date: datetime
        :param _preload_content: if False, the ApiResponse.data will
                                 be set to none and raw_data will store the
                                 HTTP response body without reading/decoding.
                                 Default is True.
        :type _preload_content: bool, optional
        :param _return_http_data_only: response data instead of ApiResponse
                                       object with status code, headers, etc
        :type _return_http_data_only: bool, optional
        :param _request_auth: set to override the auth_settings for an a single
                              request; this effectively ignores the authentication
                              in the spec for a single request.
        :type _request_auth: dict, optional
        :type _content_type: string, optional: force content-type for the request
        :return: Returns the result object.
        :rtype: tuple(UsageMonitoringResponse, status_code(int), headers(HTTPHeaderDict))
        """

        _params = locals()

        _all_params = ["metric_type", "start_date", "end_date"]
        _all_params.extend(
            [
                "async_req",
                "_return_http_data_only",
                "_preload_content",
                "_request_timeout",
                "_request_auth",
                "_content_type",
                "_headers",
            ]
        )

        # validate the arguments
        for _key, _val in _params["kwargs"].items():
            if _key not in _all_params:
                raise ApiTypeError(
                    "Got an unexpected keyword argument '%s'"
                    " to method get_usage_summary" % _key
                )
            _params[_key] = _val
        del _params["kwargs"]

        _collection_formats = {}

        # process the path parameters
        _path_params = {}

        # process the query parameters
        _query_params = []
        if _params.get("metric_type") is not None:
            _query_params.append(("metricType", _params["metric_type"]))

        if _params.get("start_date") is not None:
            if isinstance(_params["start_date"], datetime):
                _query_params.append(
                    (
                        "startDate",
                        _params["start_date"].strftime(
                            self.api_client.configuration.datetime_format
                        ),
                    )
                )
            else:
                _query_params.append(("startDate", _params["start_date"]))

        if _params.get("end_date") is not None:
            if isinstance(_params["end_date"], datetime):
                _query_params.append(
                    (
                        "endDate",
                        _params["end_date"].strftime(
                            self.api_client.configuration.datetime_format
                        ),
                    )
                )
            else:
                _query_params.append(("endDate", _params["end_date"]))

        # process the header parameters
        _header_params = dict(_params.get("_headers", {}))
        # process the form parameters
        _form_params = []
        _files = {}
        # process the body parameter
        _body_params = None
        # set the HTTP header `Accept`
        _header_params["Accept"] = self.api_client.select_header_accept(
            ["application/json", "application/problem+json"]
        )

        # authentication setting
        _auth_settings = ["BearerAuth"]

        _response_types_map = {
            "200": "UsageMonitoringResponse",
        }

        return self.api_client.call_api(
            "/v1/usage-metrics",
            "GET",
            _path_params,
            _query_params,
            _header_params,
            body=_body_params,
            post_params=_form_params,
            files=_files,
            response_types_map=_response_types_map,
            auth_settings=_auth_settings,
            async_req=_params.get("async_req"),
            _return_http_data_only=_params.get("_return_http_data_only"),
            _preload_content=_params.get("_preload_content", True),
            _request_timeout=_params.get("_request_timeout"),
            collection_formats=_collection_formats,
            _request_auth=_params.get("_request_auth"),
        )
