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

from .basesdk import BaseSDK
from typing import Any, Mapping, Optional, Union
from unkey.py import errors, models, utils
from unkey.py._hooks import HookContext
from unkey.py.types import OptionalNullable, UNSET
from unkey.py.utils.unmarshal_json_response import unmarshal_json_response


class Internal(BaseSDK):
    def create_deployment(
        self,
        *,
        project: str,
        app: str,
        branch: str,
        environment_slug: str,
        docker_image: str,
        keyspace_id: Optional[str] = None,
        git_commit: Optional[
            Union[models.V2DeployGitCommit, models.V2DeployGitCommitTypedDict]
        ] = None,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.V2DeployCreateDeploymentResponseBody:
        r"""Create deployment

        **INTERNAL** - This endpoint is internal and may change without notice.
        Not recommended for production use.

        Creates a new deployment for a project using either a pre-built Docker image or build context.

        **Authentication**: Requires a valid root key with appropriate permissions.


        If set, this operation will use `root_key` from the global security.

        :param project: Project slug
        :param app: App slug within the project
        :param branch: Git branch name
        :param environment_slug: Environment slug (e.g., \"production\", \"staging\")
        :param docker_image: Docker image reference to deploy
        :param keyspace_id: Optional keyspace ID for authentication context
        :param git_commit: Optional git commit information
        :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.V2DeployCreateDeploymentRequestBody(
            project=project,
            app=app,
            keyspace_id=keyspace_id,
            branch=branch,
            environment_slug=environment_slug,
            docker_image=docker_image,
            git_commit=utils.get_pydantic_model(
                git_commit, Optional[models.V2DeployGitCommit]
            ),
        )

        req = self._build_request(
            method="POST",
            path="/v2/deploy.createDeployment",
            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.V2DeployCreateDeploymentRequestBody,
            ),
            allow_empty_value=None,
            allowed_fields=["root_key"],
            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(50, 1000, 1.5, 10000), True
                )

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["5XX"])

        http_res = self.do_request(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="deploy.createDeployment",
                oauth2_scopes=None,
                security_source=self.sdk_configuration.security,
            ),
            request=req,
            error_status_codes=["400", "401", "403", "404", "429", "4XX", "500", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "201", "application/json"):
            return unmarshal_json_response(
                models.V2DeployCreateDeploymentResponseBody, http_res
            )
        if utils.match_response(http_res, "400", "application/json"):
            response_data = unmarshal_json_response(
                errors.BadRequestErrorResponseData, http_res
            )
            raise errors.BadRequestErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "401", "application/json"):
            response_data = unmarshal_json_response(
                errors.UnauthorizedErrorResponseData, http_res
            )
            raise errors.UnauthorizedErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "403", "application/json"):
            response_data = unmarshal_json_response(
                errors.ForbiddenErrorResponseData, http_res
            )
            raise errors.ForbiddenErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "404", "application/json"):
            response_data = unmarshal_json_response(
                errors.NotFoundErrorResponseData, http_res
            )
            raise errors.NotFoundErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "429", "application/problem+json"):
            response_data = unmarshal_json_response(
                errors.TooManyRequestsErrorResponseData, http_res
            )
            raise errors.TooManyRequestsErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "500", "application/json"):
            response_data = unmarshal_json_response(
                errors.InternalServerErrorResponseData, http_res
            )
            raise errors.InternalServerErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.APIError("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.APIError("API error occurred", http_res, http_res_text)

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

    async def create_deployment_async(
        self,
        *,
        project: str,
        app: str,
        branch: str,
        environment_slug: str,
        docker_image: str,
        keyspace_id: Optional[str] = None,
        git_commit: Optional[
            Union[models.V2DeployGitCommit, models.V2DeployGitCommitTypedDict]
        ] = None,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.V2DeployCreateDeploymentResponseBody:
        r"""Create deployment

        **INTERNAL** - This endpoint is internal and may change without notice.
        Not recommended for production use.

        Creates a new deployment for a project using either a pre-built Docker image or build context.

        **Authentication**: Requires a valid root key with appropriate permissions.


        If set, this operation will use `root_key` from the global security.

        :param project: Project slug
        :param app: App slug within the project
        :param branch: Git branch name
        :param environment_slug: Environment slug (e.g., \"production\", \"staging\")
        :param docker_image: Docker image reference to deploy
        :param keyspace_id: Optional keyspace ID for authentication context
        :param git_commit: Optional git commit information
        :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.V2DeployCreateDeploymentRequestBody(
            project=project,
            app=app,
            keyspace_id=keyspace_id,
            branch=branch,
            environment_slug=environment_slug,
            docker_image=docker_image,
            git_commit=utils.get_pydantic_model(
                git_commit, Optional[models.V2DeployGitCommit]
            ),
        )

        req = self._build_request_async(
            method="POST",
            path="/v2/deploy.createDeployment",
            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.V2DeployCreateDeploymentRequestBody,
            ),
            allow_empty_value=None,
            allowed_fields=["root_key"],
            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(50, 1000, 1.5, 10000), True
                )

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["5XX"])

        http_res = await self.do_request_async(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="deploy.createDeployment",
                oauth2_scopes=None,
                security_source=self.sdk_configuration.security,
            ),
            request=req,
            error_status_codes=["400", "401", "403", "404", "429", "4XX", "500", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "201", "application/json"):
            return unmarshal_json_response(
                models.V2DeployCreateDeploymentResponseBody, http_res
            )
        if utils.match_response(http_res, "400", "application/json"):
            response_data = unmarshal_json_response(
                errors.BadRequestErrorResponseData, http_res
            )
            raise errors.BadRequestErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "401", "application/json"):
            response_data = unmarshal_json_response(
                errors.UnauthorizedErrorResponseData, http_res
            )
            raise errors.UnauthorizedErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "403", "application/json"):
            response_data = unmarshal_json_response(
                errors.ForbiddenErrorResponseData, http_res
            )
            raise errors.ForbiddenErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "404", "application/json"):
            response_data = unmarshal_json_response(
                errors.NotFoundErrorResponseData, http_res
            )
            raise errors.NotFoundErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "429", "application/problem+json"):
            response_data = unmarshal_json_response(
                errors.TooManyRequestsErrorResponseData, http_res
            )
            raise errors.TooManyRequestsErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "500", "application/json"):
            response_data = unmarshal_json_response(
                errors.InternalServerErrorResponseData, http_res
            )
            raise errors.InternalServerErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.APIError("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.APIError("API error occurred", http_res, http_res_text)

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

    def get_deployment(
        self,
        *,
        deployment_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.V2DeployGetDeploymentResponseBody:
        r"""Get deployment

        **INTERNAL** - This endpoint is internal and may change without notice.
        Not recommended for production use.

        Retrieves deployment information including status, error messages, and steps.

        **Authentication**: Requires a valid root key with appropriate permissions.


        If set, this operation will use `root_key` from the global security.

        :param deployment_id: Unique deployment identifier to retrieve
        :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.V2DeployGetDeploymentRequestBody(
            deployment_id=deployment_id,
        )

        req = self._build_request(
            method="POST",
            path="/v2/deploy.getDeployment",
            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.V2DeployGetDeploymentRequestBody
            ),
            allow_empty_value=None,
            allowed_fields=["root_key"],
            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(50, 1000, 1.5, 10000), True
                )

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["5XX"])

        http_res = self.do_request(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="deploy.getDeployment",
                oauth2_scopes=None,
                security_source=self.sdk_configuration.security,
            ),
            request=req,
            error_status_codes=["400", "401", "403", "404", "429", "4XX", "500", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(
                models.V2DeployGetDeploymentResponseBody, http_res
            )
        if utils.match_response(http_res, "400", "application/json"):
            response_data = unmarshal_json_response(
                errors.BadRequestErrorResponseData, http_res
            )
            raise errors.BadRequestErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "401", "application/json"):
            response_data = unmarshal_json_response(
                errors.UnauthorizedErrorResponseData, http_res
            )
            raise errors.UnauthorizedErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "403", "application/json"):
            response_data = unmarshal_json_response(
                errors.ForbiddenErrorResponseData, http_res
            )
            raise errors.ForbiddenErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "404", "application/json"):
            response_data = unmarshal_json_response(
                errors.NotFoundErrorResponseData, http_res
            )
            raise errors.NotFoundErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "429", "application/problem+json"):
            response_data = unmarshal_json_response(
                errors.TooManyRequestsErrorResponseData, http_res
            )
            raise errors.TooManyRequestsErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "500", "application/json"):
            response_data = unmarshal_json_response(
                errors.InternalServerErrorResponseData, http_res
            )
            raise errors.InternalServerErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.APIError("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.APIError("API error occurred", http_res, http_res_text)

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

    async def get_deployment_async(
        self,
        *,
        deployment_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.V2DeployGetDeploymentResponseBody:
        r"""Get deployment

        **INTERNAL** - This endpoint is internal and may change without notice.
        Not recommended for production use.

        Retrieves deployment information including status, error messages, and steps.

        **Authentication**: Requires a valid root key with appropriate permissions.


        If set, this operation will use `root_key` from the global security.

        :param deployment_id: Unique deployment identifier to retrieve
        :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.V2DeployGetDeploymentRequestBody(
            deployment_id=deployment_id,
        )

        req = self._build_request_async(
            method="POST",
            path="/v2/deploy.getDeployment",
            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.V2DeployGetDeploymentRequestBody
            ),
            allow_empty_value=None,
            allowed_fields=["root_key"],
            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(50, 1000, 1.5, 10000), True
                )

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["5XX"])

        http_res = await self.do_request_async(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="deploy.getDeployment",
                oauth2_scopes=None,
                security_source=self.sdk_configuration.security,
            ),
            request=req,
            error_status_codes=["400", "401", "403", "404", "429", "4XX", "500", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(
                models.V2DeployGetDeploymentResponseBody, http_res
            )
        if utils.match_response(http_res, "400", "application/json"):
            response_data = unmarshal_json_response(
                errors.BadRequestErrorResponseData, http_res
            )
            raise errors.BadRequestErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "401", "application/json"):
            response_data = unmarshal_json_response(
                errors.UnauthorizedErrorResponseData, http_res
            )
            raise errors.UnauthorizedErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "403", "application/json"):
            response_data = unmarshal_json_response(
                errors.ForbiddenErrorResponseData, http_res
            )
            raise errors.ForbiddenErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "404", "application/json"):
            response_data = unmarshal_json_response(
                errors.NotFoundErrorResponseData, http_res
            )
            raise errors.NotFoundErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "429", "application/problem+json"):
            response_data = unmarshal_json_response(
                errors.TooManyRequestsErrorResponseData, http_res
            )
            raise errors.TooManyRequestsErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "500", "application/json"):
            response_data = unmarshal_json_response(
                errors.InternalServerErrorResponseData, http_res
            )
            raise errors.InternalServerErrorResponse(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.APIError("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.APIError("API error occurred", http_res, http_res_text)

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