# 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.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..types.promote_to_assistant_response import PromoteToAssistantResponse
from ..types.workflow_list_response import WorkflowListResponse
from ..types.workflow_response import WorkflowResponse

# 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 list_workflows(
        self,
        *,
        external_id: typing.Optional[str] = None,
        active_only: typing.Optional[bool] = None,
        limit: typing.Optional[int] = None,
        offset: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[WorkflowListResponse]:
        """
        List workflows for the authenticated organization.

        Parameters
        ----------
        external_id : typing.Optional[str]
            Filter by external ID

        active_only : typing.Optional[bool]
            Return only active workflows

        limit : typing.Optional[int]
            Maximum items to return

        offset : typing.Optional[int]
            Number of items to skip

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

        Returns
        -------
        HttpResponse[WorkflowListResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/workflows",
            method="GET",
            params={
                "external_id": external_id,
                "active_only": active_only,
                "limit": limit,
                "offset": offset,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    WorkflowListResponse,
                    parse_obj_as(
                        type_=WorkflowListResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            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)

    def create_workflow(
        self,
        *,
        name: str,
        definition: typing.Dict[str, typing.Any],
        description: typing.Optional[str] = OMIT,
        external_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[WorkflowResponse]:
        """
        Create a new workflow or update existing if external_id matches (upsert).

        Parameters
        ----------
        name : str
            Workflow name

        definition : typing.Dict[str, typing.Any]
            Flow-plate workflow JSON definition

        description : typing.Optional[str]
            Workflow description

        external_id : typing.Optional[str]
            Flow-plate internal flow ID for correlation

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

        Returns
        -------
        HttpResponse[WorkflowResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/workflows",
            method="POST",
            json={
                "name": name,
                "description": description,
                "definition": definition,
                "external_id": external_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    WorkflowResponse,
                    parse_obj_as(
                        type_=WorkflowResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            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)

    def get_workflow(
        self, workflow_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[WorkflowResponse]:
        """
        Get a workflow by ID.

        Parameters
        ----------
        workflow_id : str

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

        Returns
        -------
        HttpResponse[WorkflowResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/workflows/{jsonable_encoder(workflow_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    WorkflowResponse,
                    parse_obj_as(
                        type_=WorkflowResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            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)

    def delete_workflow(
        self, workflow_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[None]:
        """
        Soft delete a workflow and unlink any associated assistant.

        Parameters
        ----------
        workflow_id : str

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

        Returns
        -------
        HttpResponse[None]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/workflows/{jsonable_encoder(workflow_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return HttpResponse(response=_response, data=None)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            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)

    def update_workflow(
        self,
        workflow_id: str,
        *,
        name: typing.Optional[str] = OMIT,
        description: typing.Optional[str] = OMIT,
        definition: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        is_active: typing.Optional[bool] = OMIT,
        external_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[WorkflowResponse]:
        """
        Update a workflow.

        Parameters
        ----------
        workflow_id : str

        name : typing.Optional[str]

        description : typing.Optional[str]

        definition : typing.Optional[typing.Dict[str, typing.Any]]
            Updated workflow definition

        is_active : typing.Optional[bool]
            Active status

        external_id : typing.Optional[str]
            Flow-plate internal flow ID for correlation

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

        Returns
        -------
        HttpResponse[WorkflowResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/workflows/{jsonable_encoder(workflow_id)}",
            method="PATCH",
            json={
                "name": name,
                "description": description,
                "definition": definition,
                "is_active": is_active,
                "external_id": external_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    WorkflowResponse,
                    parse_obj_as(
                        type_=WorkflowResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            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)

    def promote_workflow_to_assistant(
        self,
        workflow_id: str,
        *,
        name: typing.Optional[str] = OMIT,
        description: typing.Optional[str] = OMIT,
        primary_node_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[PromoteToAssistantResponse]:
        """
        Promote a workflow to an assistant.

        Parameters
        ----------
        workflow_id : str

        name : typing.Optional[str]
            Assistant name (defaults to workflow name)

        description : typing.Optional[str]
            Assistant description

        primary_node_id : typing.Optional[str]
            Node ID to use for settings (required if multiple FreddyLLM nodes)

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

        Returns
        -------
        HttpResponse[PromoteToAssistantResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/workflows/{jsonable_encoder(workflow_id)}/promote-to-assistant",
            method="POST",
            json={
                "name": name,
                "description": description,
                "primary_node_id": primary_node_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    PromoteToAssistantResponse,
                    parse_obj_as(
                        type_=PromoteToAssistantResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            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 list_workflows(
        self,
        *,
        external_id: typing.Optional[str] = None,
        active_only: typing.Optional[bool] = None,
        limit: typing.Optional[int] = None,
        offset: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[WorkflowListResponse]:
        """
        List workflows for the authenticated organization.

        Parameters
        ----------
        external_id : typing.Optional[str]
            Filter by external ID

        active_only : typing.Optional[bool]
            Return only active workflows

        limit : typing.Optional[int]
            Maximum items to return

        offset : typing.Optional[int]
            Number of items to skip

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

        Returns
        -------
        AsyncHttpResponse[WorkflowListResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/workflows",
            method="GET",
            params={
                "external_id": external_id,
                "active_only": active_only,
                "limit": limit,
                "offset": offset,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    WorkflowListResponse,
                    parse_obj_as(
                        type_=WorkflowListResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            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)

    async def create_workflow(
        self,
        *,
        name: str,
        definition: typing.Dict[str, typing.Any],
        description: typing.Optional[str] = OMIT,
        external_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[WorkflowResponse]:
        """
        Create a new workflow or update existing if external_id matches (upsert).

        Parameters
        ----------
        name : str
            Workflow name

        definition : typing.Dict[str, typing.Any]
            Flow-plate workflow JSON definition

        description : typing.Optional[str]
            Workflow description

        external_id : typing.Optional[str]
            Flow-plate internal flow ID for correlation

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

        Returns
        -------
        AsyncHttpResponse[WorkflowResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/workflows",
            method="POST",
            json={
                "name": name,
                "description": description,
                "definition": definition,
                "external_id": external_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    WorkflowResponse,
                    parse_obj_as(
                        type_=WorkflowResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            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)

    async def get_workflow(
        self, workflow_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[WorkflowResponse]:
        """
        Get a workflow by ID.

        Parameters
        ----------
        workflow_id : str

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

        Returns
        -------
        AsyncHttpResponse[WorkflowResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/workflows/{jsonable_encoder(workflow_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    WorkflowResponse,
                    parse_obj_as(
                        type_=WorkflowResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            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)

    async def delete_workflow(
        self, workflow_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[None]:
        """
        Soft delete a workflow and unlink any associated assistant.

        Parameters
        ----------
        workflow_id : str

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

        Returns
        -------
        AsyncHttpResponse[None]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/workflows/{jsonable_encoder(workflow_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return AsyncHttpResponse(response=_response, data=None)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            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)

    async def update_workflow(
        self,
        workflow_id: str,
        *,
        name: typing.Optional[str] = OMIT,
        description: typing.Optional[str] = OMIT,
        definition: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        is_active: typing.Optional[bool] = OMIT,
        external_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[WorkflowResponse]:
        """
        Update a workflow.

        Parameters
        ----------
        workflow_id : str

        name : typing.Optional[str]

        description : typing.Optional[str]

        definition : typing.Optional[typing.Dict[str, typing.Any]]
            Updated workflow definition

        is_active : typing.Optional[bool]
            Active status

        external_id : typing.Optional[str]
            Flow-plate internal flow ID for correlation

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

        Returns
        -------
        AsyncHttpResponse[WorkflowResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/workflows/{jsonable_encoder(workflow_id)}",
            method="PATCH",
            json={
                "name": name,
                "description": description,
                "definition": definition,
                "is_active": is_active,
                "external_id": external_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    WorkflowResponse,
                    parse_obj_as(
                        type_=WorkflowResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            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)

    async def promote_workflow_to_assistant(
        self,
        workflow_id: str,
        *,
        name: typing.Optional[str] = OMIT,
        description: typing.Optional[str] = OMIT,
        primary_node_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[PromoteToAssistantResponse]:
        """
        Promote a workflow to an assistant.

        Parameters
        ----------
        workflow_id : str

        name : typing.Optional[str]
            Assistant name (defaults to workflow name)

        description : typing.Optional[str]
            Assistant description

        primary_node_id : typing.Optional[str]
            Node ID to use for settings (required if multiple FreddyLLM nodes)

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

        Returns
        -------
        AsyncHttpResponse[PromoteToAssistantResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/workflows/{jsonable_encoder(workflow_id)}/promote-to-assistant",
            method="POST",
            json={
                "name": name,
                "description": description,
                "primary_node_id": primary_node_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    PromoteToAssistantResponse,
                    parse_obj_as(
                        type_=PromoteToAssistantResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            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)
