"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
# @generated-id: 27db549ac58a

from .basesdk import BaseSDK
from .httpclient import AsyncHttpClient, ClientOwner, HttpClient, close_clients
from .sdkconfiguration import SDKConfiguration
from .utils.logger import Logger, get_default_logger
from .utils.retries import RetryConfig
import httpx
import importlib
from mistralai.workflows.worker_client import errors, models, utils
from mistralai.workflows.worker_client._hooks import HookContext, SDKHooks
from mistralai.workflows.worker_client.types import OptionalNullable, UNSET
from mistralai.workflows.worker_client.utils.unmarshal_json_response import (
    unmarshal_json_response,
)
import sys
from typing import Any, List, Mapping, Optional, TYPE_CHECKING, Union, cast
import weakref

if TYPE_CHECKING:
    from mistralai.workflows.worker_client.events import Events


class PrivateWorkerClient(BaseSDK):
    r"""Abraxas app: Abraxas service API"""

    events: "Events"
    _sub_sdk_map = {
        "events": ("mistralai.workflows.worker_client.events", "Events"),
    }

    def __init__(
        self,
        server_url: str,
        client: Optional[HttpClient] = None,
        async_client: Optional[AsyncHttpClient] = None,
        retry_config: OptionalNullable[RetryConfig] = UNSET,
        timeout_ms: Optional[int] = None,
        debug_logger: Optional[Logger] = None,
    ) -> None:
        r"""Instantiates the SDK configuring it with the provided parameters.

        :param server_idx: The index of the server to use for all methods
        :param server_url: The server URL to use for all methods
        :param url_params: Parameters to optionally template the server URL with
        :param client: The HTTP client to use for all synchronous methods
        :param async_client: The Async HTTP client to use for all asynchronous methods
        :param retry_config: The retry configuration to use for all supported methods
        :param timeout_ms: Optional request timeout applied to each operation in milliseconds
        """
        client_supplied = True
        if client is None:
            client = httpx.Client(follow_redirects=True)
            client_supplied = False

        assert issubclass(
            type(client), HttpClient
        ), "The provided client must implement the HttpClient protocol."

        async_client_supplied = True
        if async_client is None:
            async_client = httpx.AsyncClient(follow_redirects=True)
            async_client_supplied = False

        if debug_logger is None:
            debug_logger = get_default_logger()

        assert issubclass(
            type(async_client), AsyncHttpClient
        ), "The provided async_client must implement the AsyncHttpClient protocol."

        BaseSDK.__init__(
            self,
            SDKConfiguration(
                client=client,
                client_supplied=client_supplied,
                async_client=async_client,
                async_client_supplied=async_client_supplied,
                server_url=server_url,
                retry_config=retry_config,
                timeout_ms=timeout_ms,
                debug_logger=debug_logger,
            ),
            parent_ref=self,
        )

        hooks = SDKHooks()

        # pylint: disable=protected-access
        self.sdk_configuration.__dict__["_hooks"] = hooks

        self.sdk_configuration = hooks.sdk_init(self.sdk_configuration)

        weakref.finalize(
            self,
            close_clients,
            cast(ClientOwner, self.sdk_configuration),
            self.sdk_configuration.client,
            self.sdk_configuration.client_supplied,
            self.sdk_configuration.async_client,
            self.sdk_configuration.async_client_supplied,
        )

    def dynamic_import(self, modname, retries=3):
        for attempt in range(retries):
            try:
                return importlib.import_module(modname)
            except KeyError:
                # Clear any half-initialized module and retry
                sys.modules.pop(modname, None)
                if attempt == retries - 1:
                    break
        raise KeyError(f"Failed to import module '{modname}' after {retries} attempts")

    def __getattr__(self, name: str):
        if name in self._sub_sdk_map:
            module_path, class_name = self._sub_sdk_map[name]
            try:
                module = self.dynamic_import(module_path)
                klass = getattr(module, class_name)
                instance = klass(self.sdk_configuration, parent_ref=self)
                setattr(self, name, instance)
                return instance
            except ImportError as e:
                raise AttributeError(
                    f"Failed to import module {module_path} for attribute {name}: {e}"
                ) from e
            except AttributeError as e:
                raise AttributeError(
                    f"Failed to find class {class_name} in module {module_path} for attribute {name}: {e}"
                ) from e

        raise AttributeError(
            f"'{type(self).__name__}' object has no attribute '{name}'"
        )

    def __dir__(self):
        default_attrs = list(super().__dir__())
        lazy_attrs = list(self._sub_sdk_map.keys())
        return sorted(list(set(default_attrs + lazy_attrs)))

    def __enter__(self):
        return self

    async def __aenter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if (
            self.sdk_configuration.client is not None
            and not self.sdk_configuration.client_supplied
        ):
            self.sdk_configuration.client.close()
        self.sdk_configuration.client = None

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        if (
            self.sdk_configuration.async_client is not None
            and not self.sdk_configuration.async_client_supplied
        ):
            await self.sdk_configuration.async_client.aclose()
        self.sdk_configuration.async_client = None

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

        :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)
        req = self._build_request(
            method="GET",
            path="/v1/workflows/workers/whoami",
            base_url=base_url,
            url_variables=url_variables,
            request=None,
            request_body_required=False,
            request_has_path_params=False,
            request_has_query_params=False,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            allow_empty_value=None,
            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="get_worker_info_v1_workflows_workers_whoami_get",
                oauth2_scopes=None,
                security_source=None,
            ),
            request=req,
            error_status_codes=["4XX", "5XX"],
            retry_config=retry_config,
        )

        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(models.WorkerInfo, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.SDKDefaultError("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 errors.SDKDefaultError("API error occurred", http_res, http_res_text)

        raise errors.SDKDefaultError("Unexpected response received", http_res)

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

        :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)
        req = self._build_request_async(
            method="GET",
            path="/v1/workflows/workers/whoami",
            base_url=base_url,
            url_variables=url_variables,
            request=None,
            request_body_required=False,
            request_has_path_params=False,
            request_has_query_params=False,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            allow_empty_value=None,
            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="get_worker_info_v1_workflows_workers_whoami_get",
                oauth2_scopes=None,
                security_source=None,
            ),
            request=req,
            error_status_codes=["4XX", "5XX"],
            retry_config=retry_config,
        )

        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(models.WorkerInfo, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.SDKDefaultError("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 errors.SDKDefaultError("API error occurred", http_res, http_res_text)

        raise errors.SDKDefaultError("Unexpected response received", http_res)

    def executor_identity(
        self,
        *,
        execution_token: str,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.ExecutorIdentityResponse:
        r"""Get Executor Identity

        :param execution_token:
        :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.ExecutorIdentityRequest(
            execution_token=execution_token,
        )

        req = self._build_request(
            method="POST",
            path="/v1/workflows/workers/executor-identity",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            request_has_path_params=False,
            request_has_query_params=False,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            get_serialized_body=lambda: utils.serialize_request_body(
                request, False, False, "json", models.ExecutorIdentityRequest
            ),
            allow_empty_value=None,
            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="get_executor_identity_v1_workflows_workers_executor_identity_post",
                oauth2_scopes=None,
                security_source=None,
            ),
            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.ExecutorIdentityResponse, http_res)
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res
            )
            raise errors.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.SDKDefaultError("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 errors.SDKDefaultError("API error occurred", http_res, http_res_text)

        raise errors.SDKDefaultError("Unexpected response received", http_res)

    async def executor_identity_async(
        self,
        *,
        execution_token: str,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.ExecutorIdentityResponse:
        r"""Get Executor Identity

        :param execution_token:
        :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.ExecutorIdentityRequest(
            execution_token=execution_token,
        )

        req = self._build_request_async(
            method="POST",
            path="/v1/workflows/workers/executor-identity",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            request_has_path_params=False,
            request_has_query_params=False,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            get_serialized_body=lambda: utils.serialize_request_body(
                request, False, False, "json", models.ExecutorIdentityRequest
            ),
            allow_empty_value=None,
            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="get_executor_identity_v1_workflows_workers_executor_identity_post",
                oauth2_scopes=None,
                security_source=None,
            ),
            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.ExecutorIdentityResponse, http_res)
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res
            )
            raise errors.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.SDKDefaultError("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 errors.SDKDefaultError("API error occurred", http_res, http_res_text)

        raise errors.SDKDefaultError("Unexpected response received", http_res)

    def heartbeat(
        self,
        *,
        workflow_registration_refs: Optional[
            Union[
                List[models.WorkflowRegistrationRefInput],
                List[models.WorkflowRegistrationRefInputTypedDict],
            ]
        ] = None,
        workflow_version_refs: Optional[
            Union[
                List[models.WorkflowRegistrationRefInput],
                List[models.WorkflowRegistrationRefInputTypedDict],
            ]
        ] = None,
        deployment_name: OptionalNullable[str] = UNSET,
        worker_name: OptionalNullable[str] = UNSET,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.WorkerHeartbeatResponse:
        r"""Heartbeat

        Lightweight heartbeat to refresh worker activity TTL.

        :param workflow_registration_refs: List of workflow registration references to heartbeat
        :param workflow_version_refs: Deprecated: use workflow_registration_refs
        :param deployment_name: Name of the deployment this worker belongs to
        :param worker_name: Human-readable name of this worker process (hostname or pod name)
        :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.WorkerHeartbeatRequest(
            workflow_registration_refs=utils.get_pydantic_model(
                workflow_registration_refs,
                Optional[List[models.WorkflowRegistrationRefInput]],
            ),
            workflow_version_refs=utils.get_pydantic_model(
                workflow_version_refs,
                Optional[List[models.WorkflowRegistrationRefInput]],
            ),
            deployment_name=deployment_name,
            worker_name=worker_name,
        )

        req = self._build_request(
            method="POST",
            path="/v1/workflows/workers/heartbeat",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            request_has_path_params=False,
            request_has_query_params=False,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            get_serialized_body=lambda: utils.serialize_request_body(
                request, False, False, "json", models.WorkerHeartbeatRequest
            ),
            allow_empty_value=None,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config
            else:
                retries = utils.RetryConfig(
                    "backoff", utils.BackoffStrategy(500, 60000, 1.5, 30000), True
                )

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

        http_res = self.do_request(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="heartbeat_v1_workflows_workers_heartbeat_post",
                oauth2_scopes=None,
                security_source=None,
            ),
            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.WorkerHeartbeatResponse, http_res)
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res
            )
            raise errors.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.SDKDefaultError("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 errors.SDKDefaultError("API error occurred", http_res, http_res_text)

        raise errors.SDKDefaultError("Unexpected response received", http_res)

    async def heartbeat_async(
        self,
        *,
        workflow_registration_refs: Optional[
            Union[
                List[models.WorkflowRegistrationRefInput],
                List[models.WorkflowRegistrationRefInputTypedDict],
            ]
        ] = None,
        workflow_version_refs: Optional[
            Union[
                List[models.WorkflowRegistrationRefInput],
                List[models.WorkflowRegistrationRefInputTypedDict],
            ]
        ] = None,
        deployment_name: OptionalNullable[str] = UNSET,
        worker_name: OptionalNullable[str] = UNSET,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.WorkerHeartbeatResponse:
        r"""Heartbeat

        Lightweight heartbeat to refresh worker activity TTL.

        :param workflow_registration_refs: List of workflow registration references to heartbeat
        :param workflow_version_refs: Deprecated: use workflow_registration_refs
        :param deployment_name: Name of the deployment this worker belongs to
        :param worker_name: Human-readable name of this worker process (hostname or pod name)
        :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.WorkerHeartbeatRequest(
            workflow_registration_refs=utils.get_pydantic_model(
                workflow_registration_refs,
                Optional[List[models.WorkflowRegistrationRefInput]],
            ),
            workflow_version_refs=utils.get_pydantic_model(
                workflow_version_refs,
                Optional[List[models.WorkflowRegistrationRefInput]],
            ),
            deployment_name=deployment_name,
            worker_name=worker_name,
        )

        req = self._build_request_async(
            method="POST",
            path="/v1/workflows/workers/heartbeat",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            request_has_path_params=False,
            request_has_query_params=False,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            get_serialized_body=lambda: utils.serialize_request_body(
                request, False, False, "json", models.WorkerHeartbeatRequest
            ),
            allow_empty_value=None,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config
            else:
                retries = utils.RetryConfig(
                    "backoff", utils.BackoffStrategy(500, 60000, 1.5, 30000), True
                )

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["408", "413", "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="heartbeat_v1_workflows_workers_heartbeat_post",
                oauth2_scopes=None,
                security_source=None,
            ),
            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.WorkerHeartbeatResponse, http_res)
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res
            )
            raise errors.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.SDKDefaultError("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 errors.SDKDefaultError("API error occurred", http_res, http_res_text)

        raise errors.SDKDefaultError("Unexpected response received", http_res)

    def register_workflow_definitions(
        self,
        *,
        definitions: Union[
            List[models.WorkflowSpecWithTaskQueue],
            List[models.WorkflowSpecWithTaskQueueTypedDict],
        ],
        deployment_name: OptionalNullable[str] = UNSET,
        worker_name: OptionalNullable[str] = UNSET,
        deployment_location: OptionalNullable[
            Union[models.DeploymentLocation, models.DeploymentLocationTypedDict]
        ] = UNSET,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.WorkflowSpecsRegisterResponse:
        r"""Register Workflow Definitions

        Register workflow specs. This endpoint is only meant to be used by workers.

        :param definitions: List of workflow specs to register
        :param deployment_name: Name of the deployment this worker belongs to
        :param worker_name: Human-readable name of this worker process (hostname or pod name)
        :param deployment_location: Metadata about where this deployment is running (local, k8s, etc.)
        :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.WorkflowSpecsRegisterRequest(
            definitions=utils.get_pydantic_model(
                definitions, List[models.WorkflowSpecWithTaskQueue]
            ),
            deployment_name=deployment_name,
            worker_name=worker_name,
            deployment_location=utils.get_pydantic_model(
                deployment_location, OptionalNullable[models.DeploymentLocation]
            ),
        )

        req = self._build_request(
            method="POST",
            path="/v1/workflows/register",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            request_has_path_params=False,
            request_has_query_params=False,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            get_serialized_body=lambda: utils.serialize_request_body(
                request, False, False, "json", models.WorkflowSpecsRegisterRequest
            ),
            allow_empty_value=None,
            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="register_workflow_definitions_v1_workflows_register_post",
                oauth2_scopes=None,
                security_source=None,
            ),
            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.WorkflowSpecsRegisterResponse, http_res
            )
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res
            )
            raise errors.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.SDKDefaultError("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 errors.SDKDefaultError("API error occurred", http_res, http_res_text)

        raise errors.SDKDefaultError("Unexpected response received", http_res)

    async def register_workflow_definitions_async(
        self,
        *,
        definitions: Union[
            List[models.WorkflowSpecWithTaskQueue],
            List[models.WorkflowSpecWithTaskQueueTypedDict],
        ],
        deployment_name: OptionalNullable[str] = UNSET,
        worker_name: OptionalNullable[str] = UNSET,
        deployment_location: OptionalNullable[
            Union[models.DeploymentLocation, models.DeploymentLocationTypedDict]
        ] = UNSET,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.WorkflowSpecsRegisterResponse:
        r"""Register Workflow Definitions

        Register workflow specs. This endpoint is only meant to be used by workers.

        :param definitions: List of workflow specs to register
        :param deployment_name: Name of the deployment this worker belongs to
        :param worker_name: Human-readable name of this worker process (hostname or pod name)
        :param deployment_location: Metadata about where this deployment is running (local, k8s, etc.)
        :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.WorkflowSpecsRegisterRequest(
            definitions=utils.get_pydantic_model(
                definitions, List[models.WorkflowSpecWithTaskQueue]
            ),
            deployment_name=deployment_name,
            worker_name=worker_name,
            deployment_location=utils.get_pydantic_model(
                deployment_location, OptionalNullable[models.DeploymentLocation]
            ),
        )

        req = self._build_request_async(
            method="POST",
            path="/v1/workflows/register",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            request_has_path_params=False,
            request_has_query_params=False,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            get_serialized_body=lambda: utils.serialize_request_body(
                request, False, False, "json", models.WorkflowSpecsRegisterRequest
            ),
            allow_empty_value=None,
            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="register_workflow_definitions_v1_workflows_register_post",
                oauth2_scopes=None,
                security_source=None,
            ),
            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.WorkflowSpecsRegisterResponse, http_res
            )
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res
            )
            raise errors.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.SDKDefaultError("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 errors.SDKDefaultError("API error occurred", http_res, http_res_text)

        raise errors.SDKDefaultError("Unexpected response received", http_res)
