"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""

from .basesdk import BaseSDK
from datetime import datetime
from jsonpath import JSONPath
from polar_sdk import models, utils
from polar_sdk._hooks import HookContext
from polar_sdk.types import BaseModel, OptionalNullable, UNSET
from polar_sdk.utils.unmarshal_json_response import unmarshal_json_response
from typing import Any, Dict, List, Mapping, Optional, Union, cast


class Events(BaseSDK):
    def list(
        self,
        *,
        filter_: OptionalNullable[str] = UNSET,
        start_timestamp: OptionalNullable[datetime] = UNSET,
        end_timestamp: OptionalNullable[datetime] = UNSET,
        organization_id: OptionalNullable[
            Union[
                models.EventsListQueryParamOrganizationIDFilter,
                models.EventsListQueryParamOrganizationIDFilterTypedDict,
            ]
        ] = UNSET,
        customer_id: OptionalNullable[
            Union[
                models.EventsListQueryParamCustomerIDFilter,
                models.EventsListQueryParamCustomerIDFilterTypedDict,
            ]
        ] = UNSET,
        external_customer_id: OptionalNullable[
            Union[
                models.QueryParamExternalCustomerIDFilter,
                models.QueryParamExternalCustomerIDFilterTypedDict,
            ]
        ] = UNSET,
        meter_id: OptionalNullable[str] = UNSET,
        name: OptionalNullable[
            Union[models.NameFilter, models.NameFilterTypedDict]
        ] = UNSET,
        source: OptionalNullable[
            Union[models.SourceFilter, models.SourceFilterTypedDict]
        ] = UNSET,
        query: OptionalNullable[str] = UNSET,
        parent_id: OptionalNullable[str] = UNSET,
        depth: OptionalNullable[int] = UNSET,
        page: Optional[int] = 1,
        limit: Optional[int] = 10,
        sorting: OptionalNullable[List[models.EventSortProperty]] = UNSET,
        metadata: OptionalNullable[
            Union[
                Dict[str, models.MetadataQuery],
                Dict[str, models.MetadataQueryTypedDict],
            ]
        ] = UNSET,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.EventsListResponseEventsList:
        r"""List Events

        List events.

        **Scopes**: `events:read` `events:write`

        :param filter_: Filter events following filter clauses. JSON string following the same schema a meter filter clause.
        :param start_timestamp: Filter events after this timestamp.
        :param end_timestamp: Filter events before this timestamp.
        :param organization_id: Filter by organization ID.
        :param customer_id: Filter by customer ID.
        :param external_customer_id: Filter by external customer ID.
        :param meter_id: Filter by a meter filter clause.
        :param name: Filter by event name.
        :param source: Filter by event source.
        :param query: Query to filter events.
        :param parent_id: When combined with depth, use this event as the anchor instead of root events.
        :param depth: Fetch descendants up to this depth. When set: 0=root events only, 1=roots+children, etc. Max 5. When not set, returns all events.
        :param page: Page number, defaults to 1.
        :param limit: Size of a page, defaults to 10. Maximum is 100.
        :param sorting: Sorting criterion. Several criteria can be used simultaneously and will be applied in order. Add a minus sign `-` before the criteria name to sort by descending order.
        :param metadata: Filter by metadata key-value pairs. It uses the `deepObject` style, e.g. `?metadata[key]=value`.
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.EventsListRequest(
            filter_=filter_,
            start_timestamp=start_timestamp,
            end_timestamp=end_timestamp,
            organization_id=organization_id,
            customer_id=customer_id,
            external_customer_id=external_customer_id,
            meter_id=meter_id,
            name=name,
            source=source,
            query=query,
            parent_id=parent_id,
            depth=depth,
            page=page,
            limit=limit,
            sorting=sorting,
            metadata=metadata,
        )

        req = self._build_request(
            method="GET",
            path="/v1/events/",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=False,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = self.do_request(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="events:list",
                oauth2_scopes=None,
                security_source=self.sdk_configuration.security,
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(
                models.EventsListResponseEventsList, http_res
            )
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                models.HTTPValidationErrorData, http_res
            )
            raise models.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise models.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise models.SDKError("API error occurred", http_res, http_res_text)

        raise models.SDKError("Unexpected response received", http_res)

    async def list_async(
        self,
        *,
        filter_: OptionalNullable[str] = UNSET,
        start_timestamp: OptionalNullable[datetime] = UNSET,
        end_timestamp: OptionalNullable[datetime] = UNSET,
        organization_id: OptionalNullable[
            Union[
                models.EventsListQueryParamOrganizationIDFilter,
                models.EventsListQueryParamOrganizationIDFilterTypedDict,
            ]
        ] = UNSET,
        customer_id: OptionalNullable[
            Union[
                models.EventsListQueryParamCustomerIDFilter,
                models.EventsListQueryParamCustomerIDFilterTypedDict,
            ]
        ] = UNSET,
        external_customer_id: OptionalNullable[
            Union[
                models.QueryParamExternalCustomerIDFilter,
                models.QueryParamExternalCustomerIDFilterTypedDict,
            ]
        ] = UNSET,
        meter_id: OptionalNullable[str] = UNSET,
        name: OptionalNullable[
            Union[models.NameFilter, models.NameFilterTypedDict]
        ] = UNSET,
        source: OptionalNullable[
            Union[models.SourceFilter, models.SourceFilterTypedDict]
        ] = UNSET,
        query: OptionalNullable[str] = UNSET,
        parent_id: OptionalNullable[str] = UNSET,
        depth: OptionalNullable[int] = UNSET,
        page: Optional[int] = 1,
        limit: Optional[int] = 10,
        sorting: OptionalNullable[List[models.EventSortProperty]] = UNSET,
        metadata: OptionalNullable[
            Union[
                Dict[str, models.MetadataQuery],
                Dict[str, models.MetadataQueryTypedDict],
            ]
        ] = UNSET,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.EventsListResponseEventsList:
        r"""List Events

        List events.

        **Scopes**: `events:read` `events:write`

        :param filter_: Filter events following filter clauses. JSON string following the same schema a meter filter clause.
        :param start_timestamp: Filter events after this timestamp.
        :param end_timestamp: Filter events before this timestamp.
        :param organization_id: Filter by organization ID.
        :param customer_id: Filter by customer ID.
        :param external_customer_id: Filter by external customer ID.
        :param meter_id: Filter by a meter filter clause.
        :param name: Filter by event name.
        :param source: Filter by event source.
        :param query: Query to filter events.
        :param parent_id: When combined with depth, use this event as the anchor instead of root events.
        :param depth: Fetch descendants up to this depth. When set: 0=root events only, 1=roots+children, etc. Max 5. When not set, returns all events.
        :param page: Page number, defaults to 1.
        :param limit: Size of a page, defaults to 10. Maximum is 100.
        :param sorting: Sorting criterion. Several criteria can be used simultaneously and will be applied in order. Add a minus sign `-` before the criteria name to sort by descending order.
        :param metadata: Filter by metadata key-value pairs. It uses the `deepObject` style, e.g. `?metadata[key]=value`.
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.EventsListRequest(
            filter_=filter_,
            start_timestamp=start_timestamp,
            end_timestamp=end_timestamp,
            organization_id=organization_id,
            customer_id=customer_id,
            external_customer_id=external_customer_id,
            meter_id=meter_id,
            name=name,
            source=source,
            query=query,
            parent_id=parent_id,
            depth=depth,
            page=page,
            limit=limit,
            sorting=sorting,
            metadata=metadata,
        )

        req = self._build_request_async(
            method="GET",
            path="/v1/events/",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=False,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = await self.do_request_async(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="events:list",
                oauth2_scopes=None,
                security_source=self.sdk_configuration.security,
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(
                models.EventsListResponseEventsList, http_res
            )
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                models.HTTPValidationErrorData, http_res
            )
            raise models.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise models.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise models.SDKError("API error occurred", http_res, http_res_text)

        raise models.SDKError("Unexpected response received", http_res)

    def list_names(
        self,
        *,
        organization_id: OptionalNullable[
            Union[
                models.EventsListNamesQueryParamOrganizationIDFilter,
                models.EventsListNamesQueryParamOrganizationIDFilterTypedDict,
            ]
        ] = UNSET,
        customer_id: OptionalNullable[
            Union[
                models.EventsListNamesQueryParamCustomerIDFilter,
                models.EventsListNamesQueryParamCustomerIDFilterTypedDict,
            ]
        ] = UNSET,
        external_customer_id: OptionalNullable[
            Union[
                models.EventsListNamesQueryParamExternalCustomerIDFilter,
                models.EventsListNamesQueryParamExternalCustomerIDFilterTypedDict,
            ]
        ] = UNSET,
        source: OptionalNullable[
            Union[models.QueryParamSourceFilter, models.QueryParamSourceFilterTypedDict]
        ] = UNSET,
        query: OptionalNullable[str] = UNSET,
        page: Optional[int] = 1,
        limit: Optional[int] = 10,
        sorting: OptionalNullable[List[models.EventNamesSortProperty]] = UNSET,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> Optional[models.EventsListNamesResponse]:
        r"""List Event Names

        List event names.

        **Scopes**: `events:read` `events:write`

        :param organization_id: Filter by organization ID.
        :param customer_id: Filter by customer ID.
        :param external_customer_id: Filter by external customer ID.
        :param source: Filter by event source.
        :param query: Query to filter event names.
        :param page: Page number, defaults to 1.
        :param limit: Size of a page, defaults to 10. Maximum is 100.
        :param sorting: Sorting criterion. Several criteria can be used simultaneously and will be applied in order. Add a minus sign `-` before the criteria name to sort by descending order.
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.EventsListNamesRequest(
            organization_id=organization_id,
            customer_id=customer_id,
            external_customer_id=external_customer_id,
            source=source,
            query=query,
            page=page,
            limit=limit,
            sorting=sorting,
        )

        req = self._build_request(
            method="GET",
            path="/v1/events/names",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=False,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = self.do_request(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="events:list_names",
                oauth2_scopes=None,
                security_source=self.sdk_configuration.security,
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        def next_func() -> Optional[models.EventsListNamesResponse]:
            body = utils.unmarshal_json(http_res.text, Union[Dict[Any, Any], List[Any]])
            page = request.page if not request.page is None else 1
            next_page = page + 1

            num_pages = JSONPath("$.pagination.max_page").parse(body)
            if len(num_pages) == 0 or num_pages[0] <= page:
                return None

            if not http_res.text:
                return None
            results = JSONPath("$.items").parse(body)
            if len(results) == 0 or len(results[0]) == 0:
                return None
            limit = request.limit if not request.limit is None else 10
            if len(results[0]) < limit:
                return None

            return self.list_names(
                organization_id=organization_id,
                customer_id=customer_id,
                external_customer_id=external_customer_id,
                source=source,
                query=query,
                page=next_page,
                limit=limit,
                sorting=sorting,
                retries=retries,
            )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return models.EventsListNamesResponse(
                result=unmarshal_json_response(models.ListResourceEventName, http_res),
                next=next_func,
            )
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                models.HTTPValidationErrorData, http_res
            )
            raise models.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise models.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise models.SDKError("API error occurred", http_res, http_res_text)

        raise models.SDKError("Unexpected response received", http_res)

    async def list_names_async(
        self,
        *,
        organization_id: OptionalNullable[
            Union[
                models.EventsListNamesQueryParamOrganizationIDFilter,
                models.EventsListNamesQueryParamOrganizationIDFilterTypedDict,
            ]
        ] = UNSET,
        customer_id: OptionalNullable[
            Union[
                models.EventsListNamesQueryParamCustomerIDFilter,
                models.EventsListNamesQueryParamCustomerIDFilterTypedDict,
            ]
        ] = UNSET,
        external_customer_id: OptionalNullable[
            Union[
                models.EventsListNamesQueryParamExternalCustomerIDFilter,
                models.EventsListNamesQueryParamExternalCustomerIDFilterTypedDict,
            ]
        ] = UNSET,
        source: OptionalNullable[
            Union[models.QueryParamSourceFilter, models.QueryParamSourceFilterTypedDict]
        ] = UNSET,
        query: OptionalNullable[str] = UNSET,
        page: Optional[int] = 1,
        limit: Optional[int] = 10,
        sorting: OptionalNullable[List[models.EventNamesSortProperty]] = UNSET,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> Optional[models.EventsListNamesResponse]:
        r"""List Event Names

        List event names.

        **Scopes**: `events:read` `events:write`

        :param organization_id: Filter by organization ID.
        :param customer_id: Filter by customer ID.
        :param external_customer_id: Filter by external customer ID.
        :param source: Filter by event source.
        :param query: Query to filter event names.
        :param page: Page number, defaults to 1.
        :param limit: Size of a page, defaults to 10. Maximum is 100.
        :param sorting: Sorting criterion. Several criteria can be used simultaneously and will be applied in order. Add a minus sign `-` before the criteria name to sort by descending order.
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.EventsListNamesRequest(
            organization_id=organization_id,
            customer_id=customer_id,
            external_customer_id=external_customer_id,
            source=source,
            query=query,
            page=page,
            limit=limit,
            sorting=sorting,
        )

        req = self._build_request_async(
            method="GET",
            path="/v1/events/names",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=False,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = await self.do_request_async(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="events:list_names",
                oauth2_scopes=None,
                security_source=self.sdk_configuration.security,
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        def next_func() -> Optional[models.EventsListNamesResponse]:
            body = utils.unmarshal_json(http_res.text, Union[Dict[Any, Any], List[Any]])
            page = request.page if not request.page is None else 1
            next_page = page + 1

            num_pages = JSONPath("$.pagination.max_page").parse(body)
            if len(num_pages) == 0 or num_pages[0] <= page:
                return None

            if not http_res.text:
                return None
            results = JSONPath("$.items").parse(body)
            if len(results) == 0 or len(results[0]) == 0:
                return None
            limit = request.limit if not request.limit is None else 10
            if len(results[0]) < limit:
                return None

            return self.list_names(
                organization_id=organization_id,
                customer_id=customer_id,
                external_customer_id=external_customer_id,
                source=source,
                query=query,
                page=next_page,
                limit=limit,
                sorting=sorting,
                retries=retries,
            )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return models.EventsListNamesResponse(
                result=unmarshal_json_response(models.ListResourceEventName, http_res),
                next=next_func,
            )
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                models.HTTPValidationErrorData, http_res
            )
            raise models.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise models.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise models.SDKError("API error occurred", http_res, http_res_text)

        raise models.SDKError("Unexpected response received", http_res)

    def get(
        self,
        *,
        id: str,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.Event:
        r"""Get Event

        Get an event by ID.

        **Scopes**: `events:read` `events:write`

        :param id: The event ID.
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.EventsGetRequest(
            id=id,
        )

        req = self._build_request(
            method="GET",
            path="/v1/events/{id}",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=True,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = self.do_request(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="events:get",
                oauth2_scopes=None,
                security_source=self.sdk_configuration.security,
            ),
            request=req,
            error_status_codes=["404", "422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(models.Event, http_res)
        if utils.match_response(http_res, "404", "application/json"):
            response_data = unmarshal_json_response(
                models.ResourceNotFoundData, http_res
            )
            raise models.ResourceNotFound(response_data, http_res)
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                models.HTTPValidationErrorData, http_res
            )
            raise models.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise models.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise models.SDKError("API error occurred", http_res, http_res_text)

        raise models.SDKError("Unexpected response received", http_res)

    async def get_async(
        self,
        *,
        id: str,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.Event:
        r"""Get Event

        Get an event by ID.

        **Scopes**: `events:read` `events:write`

        :param id: The event ID.
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.EventsGetRequest(
            id=id,
        )

        req = self._build_request_async(
            method="GET",
            path="/v1/events/{id}",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=True,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = await self.do_request_async(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="events:get",
                oauth2_scopes=None,
                security_source=self.sdk_configuration.security,
            ),
            request=req,
            error_status_codes=["404", "422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(models.Event, http_res)
        if utils.match_response(http_res, "404", "application/json"):
            response_data = unmarshal_json_response(
                models.ResourceNotFoundData, http_res
            )
            raise models.ResourceNotFound(response_data, http_res)
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                models.HTTPValidationErrorData, http_res
            )
            raise models.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise models.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise models.SDKError("API error occurred", http_res, http_res_text)

        raise models.SDKError("Unexpected response received", http_res)

    def ingest(
        self,
        *,
        request: Union[models.EventsIngest, models.EventsIngestTypedDict],
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.EventsIngestResponse:
        r"""Ingest Events

        Ingest batch of events.

        **Scopes**: `events:write`

        :param request: The request object to send.
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        if not isinstance(request, BaseModel):
            request = utils.unmarshal(request, models.EventsIngest)
        request = cast(models.EventsIngest, request)

        req = self._build_request(
            method="POST",
            path="/v1/events/ingest",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            request_has_path_params=False,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            get_serialized_body=lambda: utils.serialize_request_body(
                request, False, False, "json", models.EventsIngest
            ),
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = self.do_request(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="events:ingest",
                oauth2_scopes=None,
                security_source=self.sdk_configuration.security,
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(models.EventsIngestResponse, http_res)
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                models.HTTPValidationErrorData, http_res
            )
            raise models.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise models.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise models.SDKError("API error occurred", http_res, http_res_text)

        raise models.SDKError("Unexpected response received", http_res)

    async def ingest_async(
        self,
        *,
        request: Union[models.EventsIngest, models.EventsIngestTypedDict],
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.EventsIngestResponse:
        r"""Ingest Events

        Ingest batch of events.

        **Scopes**: `events:write`

        :param request: The request object to send.
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        if not isinstance(request, BaseModel):
            request = utils.unmarshal(request, models.EventsIngest)
        request = cast(models.EventsIngest, request)

        req = self._build_request_async(
            method="POST",
            path="/v1/events/ingest",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            request_has_path_params=False,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            get_serialized_body=lambda: utils.serialize_request_body(
                request, False, False, "json", models.EventsIngest
            ),
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = await self.do_request_async(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="events:ingest",
                oauth2_scopes=None,
                security_source=self.sdk_configuration.security,
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(models.EventsIngestResponse, http_res)
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                models.HTTPValidationErrorData, http_res
            )
            raise models.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise models.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise models.SDKError("API error occurred", http_res, http_res_text)

        raise models.SDKError("Unexpected response received", http_res)
