# This file was auto-generated by Fern from our API Definition.

import typing
from json.decoder import JSONDecodeError

from ...core.api_error import ApiError
from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ...core.http_response import AsyncHttpResponse, HttpResponse
from ...core.jsonable_encoder import jsonable_encoder
from ...core.request_options import RequestOptions
from ...core.serialization import convert_and_respect_annotation_metadata
from ...core.unchecked_base_model import construct_type
from ..errors.bad_request_error import BadRequestError
from ..errors.internal_server_error import InternalServerError
from ..errors.not_found_error import NotFoundError
from ..errors.unauthorized_error import UnauthorizedError
from ..types.single_prompt_config import SinglePromptConfig
from ..types.workflow_type import WorkflowType
from .types.patch_workflow_id_request_workflow_graph import PatchWorkflowIdRequestWorkflowGraph
from .types.patch_workflow_id_response import PatchWorkflowIdResponse

# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)


class RawWorkflowsClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._client_wrapper = client_wrapper

    def update_workflow_configuration(
        self,
        id: str,
        *,
        type: WorkflowType,
        workflow_graph: typing.Optional[PatchWorkflowIdRequestWorkflowGraph] = OMIT,
        single_prompt_config: typing.Optional[SinglePromptConfig] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[PatchWorkflowIdResponse]:
        """
        Update workflow configuration for an agent. Currently available for single_prompt workflows only. For workflow_graph configurations, please use the UI.

        Parameters
        ----------
        id : str
            The ID of the workflow to update

        type : WorkflowType
            The type of workflow (single_prompt or workflow_graph)

        workflow_graph : typing.Optional[PatchWorkflowIdRequestWorkflowGraph]
            Workflow graph configuration. Required when type is workflow_graph. Exactly one of workflowGraph or singlePromptConfig must be provided.

        single_prompt_config : typing.Optional[SinglePromptConfig]
            Configuration for single_prompt workflow type. Required when type is single_prompt. Exactly one of workflowGraph or singlePromptConfig must be provided.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[PatchWorkflowIdResponse]
            Workflow updated successfully
        """
        _response = self._client_wrapper.httpx_client.request(
            f"workflow/{jsonable_encoder(id)}",
            base_url=self._client_wrapper.get_environment().atoms,
            method="PATCH",
            json={
                "type": type,
                "workflowGraph": convert_and_respect_annotation_metadata(
                    object_=workflow_graph, annotation=PatchWorkflowIdRequestWorkflowGraph, direction="write"
                ),
                "singlePromptConfig": convert_and_respect_annotation_metadata(
                    object_=single_prompt_config, annotation=SinglePromptConfig, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    PatchWorkflowIdResponse,
                    construct_type(
                        type_=PatchWorkflowIdResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


class AsyncRawWorkflowsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def update_workflow_configuration(
        self,
        id: str,
        *,
        type: WorkflowType,
        workflow_graph: typing.Optional[PatchWorkflowIdRequestWorkflowGraph] = OMIT,
        single_prompt_config: typing.Optional[SinglePromptConfig] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[PatchWorkflowIdResponse]:
        """
        Update workflow configuration for an agent. Currently available for single_prompt workflows only. For workflow_graph configurations, please use the UI.

        Parameters
        ----------
        id : str
            The ID of the workflow to update

        type : WorkflowType
            The type of workflow (single_prompt or workflow_graph)

        workflow_graph : typing.Optional[PatchWorkflowIdRequestWorkflowGraph]
            Workflow graph configuration. Required when type is workflow_graph. Exactly one of workflowGraph or singlePromptConfig must be provided.

        single_prompt_config : typing.Optional[SinglePromptConfig]
            Configuration for single_prompt workflow type. Required when type is single_prompt. Exactly one of workflowGraph or singlePromptConfig must be provided.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[PatchWorkflowIdResponse]
            Workflow updated successfully
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"workflow/{jsonable_encoder(id)}",
            base_url=self._client_wrapper.get_environment().atoms,
            method="PATCH",
            json={
                "type": type,
                "workflowGraph": convert_and_respect_annotation_metadata(
                    object_=workflow_graph, annotation=PatchWorkflowIdRequestWorkflowGraph, direction="write"
                ),
                "singlePromptConfig": convert_and_respect_annotation_metadata(
                    object_=single_prompt_config, annotation=SinglePromptConfig, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    PatchWorkflowIdResponse,
                    construct_type(
                        type_=PatchWorkflowIdResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
