# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/routes/dataflow.ipynb.

# %% auto 0
__all__ = ['GET_Dataflow_Error', 'CRUD_Dataflow_Error', 'get_dataflows', 'get_dataflow_by_id', 'update_dataflow_definition',
           'get_dataflow_tags_by_id', 'generate_tag_body', 'put_dataflow_tags_by_id', 'get_dataflow_versions',
           'get_dataflow_by_id_and_version', 'get_dataflow_execution_history', 'get_dataflow_execution_by_id',
           'execute_dataflow', 'generate_search_dataflows_to_jupyter_workspaces_body',
           'search_dataflows_to_jupyter_workspaces']

# %% ../../nbs/routes/dataflow.ipynb 2
import httpx
from typing import List

import domolibrary.client.get_data as gd
import domolibrary.client.ResponseGetData as rgd
import domolibrary.client.DomoAuth as dmda
import domolibrary.client.DomoError as dmde

# %% ../../nbs/routes/dataflow.ipynb 5
class GET_Dataflow_Error(dmde.RouteError):
    def __init__(self, res: rgd.ResponseGetData):
        super().__init__(res=res)


class CRUD_Dataflow_Error(dmde.RouteError):
    def __init__(self, res: rgd.ResponseGetData):
        super().__init__(res=res)

# %% ../../nbs/routes/dataflow.ipynb 6
@gd.route_function
async def get_dataflows(
    auth: dmda.DomoAuth,
    debug_api: bool = False,
    session: httpx.AsyncClient = None,
    parent_class: str = None,
    debug_num_stacks_to_drop=1,
) -> rgd.ResponseGetData:
    domo_instance = auth.domo_instance

    url = f"https://{domo_instance}.domo.com/api/dataprocessing/v1/dataflows"

    res= await gd.get_data(
        auth=auth,
        url=url,
        method="GET",
        debug_api=debug_api,
        session=session,
        parent_class=parent_class,
        num_stacks_to_drop=debug_num_stacks_to_drop,
    )

    if not res.is_success:
        raise GET_Dataflow_Error(res)

    return res

# %% ../../nbs/routes/dataflow.ipynb 8
@gd.route_function
async def get_dataflow_by_id(
    dataflow_id: int,
    auth: dmda.DomoAuth,
    debug_api: bool = False,
    session: httpx.AsyncClient = None,
    parent_class: str = None,
    debug_num_stacks_to_drop=1,
) -> rgd.ResponseGetData:
    domo_instance = auth.domo_instance

    url = f"https://{domo_instance}.domo.com/api/dataprocessing/v1/dataflows/{dataflow_id}"

    res= await gd.get_data(
        auth=auth,
        url=url,
        method="GET",
        debug_api=debug_api,
        session=session,
        parent_class=parent_class,
        num_stacks_to_drop=debug_num_stacks_to_drop,
    )

    if not res.is_success:
        raise GET_Dataflow_Error(res)

    return res

# %% ../../nbs/routes/dataflow.ipynb 11
@gd.route_function
async def update_dataflow_definition(
    auth: dmda.DomoAuth,
    dataflow_id : int,
    dataflow_definition : dict,
    debug_api: bool = False,
    debug_num_stacks_to_drop = 1,
    parent_class : str = None,
    session : httpx.AsyncClient = None
) -> rgd.ResponseGetData:
    
    # Construct the URL
    url = f"https://{auth.domo_instance}.domo.com/api/dataprocessing/v1/dataflows/{dataflow_id}"
    
    
    # Make the API call
    res = await gd.get_data(
        auth=auth,
        url=url,
        method="PUT",
        body=dataflow_definition,
        debug_api=debug_api,
        session = session,
        parent_class = parent_class,
        num_stacks_to_drop = debug_num_stacks_to_drop
    )
    
    # Check for successful response
    if not res.is_success:
        raise dmde.RouteError(res = res)
    
    return res

# %% ../../nbs/routes/dataflow.ipynb 12
@gd.route_function
async def get_dataflow_tags_by_id(
    auth: dmda.DomoAuth,
    dataflow_id: int,
    debug_api: bool = False,
    debug_num_stacks_to_drop : bool = False,
    session : httpx.AsyncClient = None,
    parent_class : str = None

) -> rgd.ResponseGetData:
    # Construct the URL for the GET request
    url = f"https://{auth.domo_instance}.domo.com/api/dataprocessing/v1/dataflows/{dataflow_id}/tags"
    
    # Make the GET request
    res = await gd.get_data(
        auth=auth,
        url=url,
        method="GET",
        debug_api=debug_api,
        num_stacks_to_drop = debug_num_stacks_to_drop,
        parent_class = parent_class,
        session = session
    )
    
    # Check if the request was successful
    if not res.is_success:
        raise dmde.RouteError(res = res)
    
    return res

# %% ../../nbs/routes/dataflow.ipynb 14
def generate_tag_body(dataflow_id, tag_ls) -> dict:
    return {"flowId": dataflow_id, "tags": tag_ls}

@gd.route_function
async def put_dataflow_tags_by_id(
    auth: dmda.DomoAuth,
    dataflow_id: int,
    tag_ls: List[str],
    debug_api: bool = False,
    debug_num_stacks_to_drop = 1,
    parent_class : str = None,
    session : httpx.AsyncClient = None
) -> rgd.ResponseGetData:
    
    # Construct the URL
    url = f"https://{auth.domo_instance}.domo.com/api/dataprocessing/v1/dataflows/{dataflow_id}/tags"
    
    # Generate the request body
    body = generate_tag_body(dataflow_id=dataflow_id, tag_ls=tag_ls)
    
    # Make the API call
    res = await gd.get_data(
        auth=auth,
        url=url,
        method="PUT",
        body=body,
        debug_api=debug_api,
        session = session,
        parent_class = parent_class,
        num_stacks_to_drop = debug_num_stacks_to_drop
    )
    
    # Check for successful response
    if not res.is_success:
        raise dmde.RouteError(res = res)
    
    return res

# %% ../../nbs/routes/dataflow.ipynb 17
@gd.route_function
async def get_dataflow_versions(
    dataflow_id: int,
    auth: dmda.DomoAuth,
    parent_class: str = None,
    session: httpx.AsyncClient = None,
    debug_num_stacks_to_drop=1,
    debug_api: bool = False,
):

    url = f"https://{auth.domo_instance}.domo.com/api/dataprocessing/v1/dataflows/{dataflow_id}/versions"

    res = await gd.get_data(
        auth=auth,
        session=session,
        url=url,
        method="GET",
        num_stacks_to_drop=debug_num_stacks_to_drop,
        parent_class=parent_class,
        debug_api=debug_api,
    )

    if not res.is_success:
        raise GET_Dataflow_Error(res = res)

    return res

# %% ../../nbs/routes/dataflow.ipynb 19
@gd.route_function
async def get_dataflow_by_id_and_version(
    dataflow_id: int,
    version_id: int,
    auth: dmda.DomoAuth,
    parent_class: str = None,
    session: httpx.AsyncClient = None,
    debug_num_stacks_to_drop=1,
    debug_api: bool = False,
):

    url = f"https://{auth.domo_instance}.domo.com/api/dataprocessing/v2/dataflows/{dataflow_id}/versions/{version_id}"

    res = await gd.get_data(
        auth=auth,
        session=session,
        url=url,
        method="GET",
        num_stacks_to_drop=debug_num_stacks_to_drop,
        parent_class=parent_class,
        debug_api=debug_api,
    )

    if not res.is_success:
        raise GET_Dataflow_Error(res)

    return res

# %% ../../nbs/routes/dataflow.ipynb 21
@gd.route_function
async def get_dataflow_execution_history(
    dataflow_id: int,
    auth: dmda.DomoAuth,
    maximum: int = None,
    parent_class: str = None,
    session: httpx.AsyncClient = None,
    debug_num_stacks_to_drop=1,
    debug_loop: bool = False,
    debug_api: bool = False,
):

    url = f"https://{auth.domo_instance}.domo.com/api/dataprocessing/v1/dataflows/{dataflow_id}/executions"

    def arr_fn(res):
        return res.response

    res = await gd.looper(
        auth=auth,
        session=session,
        url=url,
        loop_until_end=True if not maximum else False,
        method="GET",
        offset_params_in_body=False,
        offset_params={"offset": "offset", "limit": "limit"},
        arr_fn=arr_fn,
        maximum=maximum,
        limit=100,
        debug_num_stacks_to_drop=debug_num_stacks_to_drop,
        parent_class=parent_class,
        debug_api=debug_api,
        debug_loop=debug_loop,
    )

    if not res.is_success:
        raise GET_Dataflow_Error(res)

    return res

# %% ../../nbs/routes/dataflow.ipynb 24
@gd.route_function
async def get_dataflow_execution_by_id(
    auth: dmda.DomoAuth,
    dataflow_id: int,
    execution_id: int,
    debug_api: bool = False,
    debug_num_stacks_to_drop=1,
    parent_class: str = None,
    session: httpx.AsyncClient = None,
) -> rgd.ResponseGetData:
    url = f"https://{auth.domo_instance}.domo.com/api/dataprocessing/v1/dataflows/{dataflow_id}/executions/{execution_id}"

    res= await gd.get_data(
        auth=auth,
        url=url,
        method="GET",
        num_stacks_to_drop=debug_num_stacks_to_drop,
        parent_class=parent_class,
        debug_api=debug_api,
        session=session,
    )

    if not res.is_success:
        raise GET_Dataflow_Error(res)
    
    return res

# %% ../../nbs/routes/dataflow.ipynb 27
@gd.route_function
async def execute_dataflow(
    auth: dmda.DomoAuth,
    dataflow_id: int,
    debug_api: bool = False,
    debug_num_stacks_to_drop=1,
    parent_class: str = None,
    session: httpx.AsyncClient = None,
) -> rgd.ResponseGetData:
    url = f"https://{auth.domo_instance}.domo.com/api/dataprocessing/v1/dataflows/{dataflow_id}/executions"

    res= await gd.get_data(
        auth=auth,
        url=url,
        method="POST",
        num_stacks_to_drop=debug_num_stacks_to_drop,
        parent_class=parent_class,
        debug_api=debug_api,
        session=session,
    )
    if not res.is_success:
        raise CRUD_Dataflow_Error(res)
    
    return res

# %% ../../nbs/routes/dataflow.ipynb 30
def generate_search_dataflows_to_jupyter_workspaces_body(filter_body: dict = None, dataflow_id: int = None):
    """
    Ensure the DATA_FLOW_ID filter exists in filter_body and append the given dataflow_id to it
    (only if it’s not already present).

    Args:
        filter_body (dict): e.g. {"filters":[{"type":"DATA_FLOW_ID","values":[116]}]}
        dataflow_id (int): ID to add under the DATA_FLOW_ID filter
    """

    filter_body = filter_body or {}

    if not dataflow_id:
        return filter_body

    # 1. Make sure there's a filters list
    filters = filter_body.setdefault('filters', [])

    # 2. Try to find an existing DATA_FLOW_ID filter
    for f in filters:
        if f.get('type') == 'DATA_FLOW_ID':
            # append if it's new
            if dataflow_id not in f['values']:
                f['values'].append(dataflow_id)
            break
    else:
        # 3. If we never broke out, no filter existed—create it
        filters.append({
            'type': 'DATA_FLOW_ID',
            'values': [dataflow_id]
        })

    return filter_body

@gd.route_function
async def search_dataflows_to_jupyter_workspaces(
    auth: dmda.DomoAuth, 
    dataflow_id: int = None,
    return_raw: bool = False,
    debug_api: bool = False,
    debug_num_stacks_to_drop : int = 1,
    session : httpx.AsyncClient = None,
    parent_class : str =None,
    filter_body : dict = None
):
    filter_body = generate_search_dataflows_to_jupyter_workspaces_body(filter_body = filter_body, dataflow_id = dataflow_id)

    res = await gd.get_data(
        url=f"https://{auth.domo_instance}.domo.com/api/datascience/v1/search/notebooks",
        auth=auth,
        method="POST",
        body=filter_body,
        session = session,
        debug_api=debug_api,
        num_stacks_to_drop = debug_num_stacks_to_drop,
        parent_class = parent_class,
        
    )

    if return_raw:
        return res

    if not res.is_success:
        raise dmde.RouteError(res=res)
    

    res.response = res.response["notebooks"]

    if dataflow_id:
        if not res.response:
            raise dmde.RouteError(res = res, entity_id = dataflow_id , message = "unable to retrieve jupyter notebook data for dataflow")
        
        res.response = res.response[-1]


    return res
