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

from abc import abstractmethod
from typing import Mapping, Optional, Union

from friendli import models, utils
from friendli._hooks import HookContext
from friendli.types import UNSET, OptionalNullable
from friendli.utils import get_security_from_env

from .basesdk import AsyncSDK, BaseSDK, SyncSDK


class BaseEndpoint(BaseSDK):
    pass


class SyncEndpoint(BaseEndpoint, SyncSDK):
    def wandb_artifact_create(
        self,
        *,
        wandb_artifact_version_name: str,
        x_friendli_team: OptionalNullable[str] = UNSET,
        accelerator: OptionalNullable[
            Union[models.AcceleratorRequirement, models.AcceleratorRequirementTypedDict]
        ] = UNSET,
        autoscaling_policy: OptionalNullable[
            Union[models.AutoscalingPolicy, models.AutoscalingPolicyTypedDict]
        ] = UNSET,
        idempotency_key: OptionalNullable[str] = UNSET,
        name: OptionalNullable[str] = UNSET,
        project_id: 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.DedicatedEndpointWandbArtifactCreateResponse:
        """Create endpoint from W&B artifact

        Create an endpoint from Weights & Biases artifact. If the idempotency key is provided, the API will check if the endpoint already exists, and rollout the existing endpoint if it does. In such cases, the project id must be provided.

        :param wandb_artifact_version_name: The specific model artifact version from Weights & Biases. The referred artifact will be used to create a new endpoint in Friendli Dedicated Endpoints or rollout an existing one.
        :param x_friendli_team: ID of team to run requests as (optional parameter).
        :param accelerator: Specifies the instance type for the endpoint.
        :param autoscaling_policy: Defines autoscaling settings for the endpoint.
        :param idempotency_key: Used by Friendli Dedicated Endpoints to track which webhook automation triggered an endpoint rollout. If the `idempotencyKey` is provided, the API will check if the endpoint already exists, and rollout the existing endpoint if it does. In such cases, the `projectId` must be provided. Any unique value can be used.
        :param name: Specifies the name of your endpoint. If not provided, a name will be automatically generated for you.
        :param project_id: Specifies where endpoint will be created in your Friendli Dedicated Endpoints. If not provided, a new project will be created within your default team.
        :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.DedicatedEndpointWandbArtifactCreateRequest(
            x_friendli_team=x_friendli_team,
            dedicated_endpoint_wandb_artifact_create_body=models.DedicatedEndpointWandbArtifactCreateBody(
                wandb_artifact_version_name=wandb_artifact_version_name,
                accelerator=utils.get_pydantic_model(
                    accelerator, OptionalNullable[models.AcceleratorRequirement]
                ),
                autoscaling_policy=utils.get_pydantic_model(
                    autoscaling_policy, OptionalNullable[models.AutoscalingPolicy]
                ),
                idempotency_key=idempotency_key,
                name=name,
                project_id=project_id,
            ),
        )
        req = self._build_request(
            method="POST",
            path="/dedicated/v1/endpoint/wandb-artifact-create",
            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.dedicated_endpoint_wandb_artifact_create_body,
                False,
                False,
                "json",
                models.DedicatedEndpointWandbArtifactCreateBody,
            ),
            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, 3600000), True
                )
        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])
        http_res = self.do_request(
            hook_ctx=HookContext(
                base_url=base_url or "",
                operation_id="dedicatedEndpointWandbArtifactCreate",
                oauth2_scopes=[],
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "422", "4XX", "5XX"],
            retry_config=retry_config,
        )
        if utils.match_response(http_res, "200", "application/json"):
            return utils.unmarshal_json(
                http_res.text, models.DedicatedEndpointWandbArtifactCreateResponse
            )
        if utils.match_response(http_res, ["400", "422", "4XX"], "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise models.SDKError(
                "API error occurred", http_res.status_code, http_res_text, http_res
            )
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise models.SDKError(
                "API error occurred", http_res.status_code, http_res_text, http_res
            )
        content_type = http_res.headers.get("Content-Type")
        http_res_text = utils.stream_to_text(http_res)
        raise models.SDKError(
            f"Unexpected response received (code: {http_res.status_code}, type: {content_type})",
            http_res.status_code,
            http_res_text,
            http_res,
        )


class AsyncEndpoint(BaseEndpoint, AsyncSDK):
    async def wandb_artifact_create(
        self,
        *,
        wandb_artifact_version_name: str,
        x_friendli_team: OptionalNullable[str] = UNSET,
        accelerator: OptionalNullable[
            Union[models.AcceleratorRequirement, models.AcceleratorRequirementTypedDict]
        ] = UNSET,
        autoscaling_policy: OptionalNullable[
            Union[models.AutoscalingPolicy, models.AutoscalingPolicyTypedDict]
        ] = UNSET,
        idempotency_key: OptionalNullable[str] = UNSET,
        name: OptionalNullable[str] = UNSET,
        project_id: 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.DedicatedEndpointWandbArtifactCreateResponse:
        """Create endpoint from W&B artifact

        Create an endpoint from Weights & Biases artifact. If the idempotency key is provided, the API will check if the endpoint already exists, and rollout the existing endpoint if it does. In such cases, the project id must be provided.

        :param wandb_artifact_version_name: The specific model artifact version from Weights & Biases. The referred artifact will be used to create a new endpoint in Friendli Dedicated Endpoints or rollout an existing one.
        :param x_friendli_team: ID of team to run requests as (optional parameter).
        :param accelerator: Specifies the instance type for the endpoint.
        :param autoscaling_policy: Defines autoscaling settings for the endpoint.
        :param idempotency_key: Used by Friendli Dedicated Endpoints to track which webhook automation triggered an endpoint rollout. If the `idempotencyKey` is provided, the API will check if the endpoint already exists, and rollout the existing endpoint if it does. In such cases, the `projectId` must be provided. Any unique value can be used.
        :param name: Specifies the name of your endpoint. If not provided, a name will be automatically generated for you.
        :param project_id: Specifies where endpoint will be created in your Friendli Dedicated Endpoints. If not provided, a new project will be created within your default team.
        :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.DedicatedEndpointWandbArtifactCreateRequest(
            x_friendli_team=x_friendli_team,
            dedicated_endpoint_wandb_artifact_create_body=models.DedicatedEndpointWandbArtifactCreateBody(
                wandb_artifact_version_name=wandb_artifact_version_name,
                accelerator=utils.get_pydantic_model(
                    accelerator, OptionalNullable[models.AcceleratorRequirement]
                ),
                autoscaling_policy=utils.get_pydantic_model(
                    autoscaling_policy, OptionalNullable[models.AutoscalingPolicy]
                ),
                idempotency_key=idempotency_key,
                name=name,
                project_id=project_id,
            ),
        )
        req = self._build_request(
            method="POST",
            path="/dedicated/v1/endpoint/wandb-artifact-create",
            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.dedicated_endpoint_wandb_artifact_create_body,
                False,
                False,
                "json",
                models.DedicatedEndpointWandbArtifactCreateBody,
            ),
            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, 3600000), True
                )
        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])
        http_res = await self.do_request(
            hook_ctx=HookContext(
                base_url=base_url or "",
                operation_id="dedicatedEndpointWandbArtifactCreate",
                oauth2_scopes=[],
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "422", "4XX", "5XX"],
            retry_config=retry_config,
        )
        if utils.match_response(http_res, "200", "application/json"):
            return utils.unmarshal_json(
                http_res.text, models.DedicatedEndpointWandbArtifactCreateResponse
            )
        if utils.match_response(http_res, ["400", "422", "4XX"], "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise models.SDKError(
                "API error occurred", http_res.status_code, http_res_text, http_res
            )
        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.status_code, http_res_text, http_res
            )
        content_type = http_res.headers.get("Content-Type")
        http_res_text = await utils.stream_to_text_async(http_res)
        raise models.SDKError(
            f"Unexpected response received (code: {http_res.status_code}, type: {content_type})",
            http_res.status_code,
            http_res_text,
            http_res,
        )
