# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_FactoryJupyter.ipynb.

# %% auto 0
__all__ = ['export_jupyter_instance_accounts', 'Factory_ExportJupyterAccounts']

# %% ../nbs/00_FactoryJupyter.ipynb 1
from domolibrary_extensions.utils.factory import (
    factory_function,
    FactoryLogs, 
    FactoryResponse, FactoryConfig, FactoryMessage)

import domolibrary.client.DomoAuth as dmda


# %% ../nbs/00_FactoryJupyter.ipynb 2
import os 
import httpx
from dataclasses import dataclass, field
from typing import List, Callable

import domolibrary.classes.DomoJupyter as dmdj
import domolibrary.classes.DomoAccount as dmac
import domolibrary_extensions.pgp as depg
import domolibrary_extensions.utils.convert as decv
import domolibrary_execution.utils as dxut

# %% ../nbs/00_FactoryJupyter.ipynb 3
@factory_function(config_id_col="jupyter_instance_name")
async def export_jupyter_instance_accounts(
    res: FactoryResponse,
    config: FactoryConfig,
    logs: FactoryLogs,
    debug_api: bool = False,
    session: httpx.AsyncClient = None,
):
    auth = config.auth
    pgp_account_name = config.pgp_account_name
    export_folder = config.export_folder
    domojupyter_fn = config.domojupyter_fn

    # Step - Get Workspace
    step = FactoryMessage(stage="get workspace", is_success=False)
    res.add_message(step)

    domo_jupyter_workspace = None
    try:
        domo_jupyter_workspace = await dmdj.DomoJupyterWorkspace.get_current_workspace(
            auth=auth, debug_api=debug_api, session=session
        )
        step.is_success = True
        step.message = "workspace config retrieved"

    except Exception as e:
        message = f"no workspace retrieved - {e}"
        step.message = message
        step.is_success = False
        res.response = message
        return res

    # STEP - get workspace accounts
    step = FactoryMessage(stage="get workspace accounts", is_success=False)
    res.add_message(step)
    domo_accounts = None

    try:
        domo_accounts = await domo_jupyter_workspace.get_accounts(
            session = session,
            debug_api = debug_api,
        )
        step.is_success = True
        step.message = f"{len(domo_accounts)} accounts retrieved"

    except Exception as e:
        step.is_success = False
        message = f"no accounts retrieved {e}" 
        step.message = message
        res.response = message
        return res

    if len(domo_accounts) == 0:
        message =  "no accounts to export"
        step.message = message
        step.is_success = True
        res.response = message
        return res

    # STEP - handle pgp key
    step = FactoryMessage(stage="handle pgp key", is_success=False)
    res.add_message(step)

    pgp_key = None
    try:
        pgp_blob = dxut.read_domo_jupyter_account(
            pgp_account_name, domojupyter_fn=domojupyter_fn, is_abstract=False
        )["credentials"].strip()
        pgp_key = depg.generate_pgpy_key(pgp_blob=pgp_blob)

        step.is_success = True
        step.message = "pgp key generated"

    except Exception as e:
        step.is_success = False
        message = f"no pgp blob - {e}"
        step.message = message
        res.response = message
        return res

    # STEP - EXPORT ACCOUNTS
    step = FactoryMessage(stage="export accounts", is_success=False)
    res.add_message(step)

    def export_account(export_folder, domo_account, res):
        account_name = domo_account.name
        step = FactoryMessage(
            stage=f"export accounts - {account_name}", is_success=False
        )
        res.add_message(step)

        try:
            config = dxut.read_domo_jupyter_account(
                domo_account.alias, domojupyter_fn=domojupyter_fn
            )
            step.message = "read domojupyter_account"

            obj = domo_account.config._from_json(config).to_json()
            obj.update(
                {"account_id": domo_account.id, "domo_instance": auth.domo_instance}
            )

            export_path = os.path.join(
                export_folder,
                decv.change_suffix(decv.convert_str_file_name(account_name), ".pgp"),
            )

            output_path = step.message = depg.pgpy_encrypt(
                pgp_key=pgp_key, data=obj, output_path=export_path
            )
            step.is_success = True
            return output_path

        except Exception as e:
            message = f"unable to export {account_name} - {e}"
            step.message = message
            step.is_success = False
            return False

    export_folder = os.path.join(export_folder, "accounts")

    export_ls = [
        export_account(
            domo_account=domo_account,
            res=res,
            export_folder=export_folder,
        )
        for domo_account in domo_accounts
    ]
    export_ls = [path for path in export_ls if path]

    if not len(domo_accounts) == len(export_ls):
        step.is_success = False
        step.message = (
            f"only exporte {len(export_ls)} out of {len(domo_accounts)} accounts"
        )
        res.response = "unsuccessful export accounts"

    step.is_success = True
    step.message = f"successfully export {len(export_ls)} accounts"

    res.response = f"accounts exported to {export_folder}"
    return res

# %% ../nbs/00_FactoryJupyter.ipynb 4
@dataclass
class Factory_ExportJupyterAccounts(FactoryConfig):
    auth : dmda.DomoAuth
    domojupyter_fn : Callable = None
    jupyter_instance_name : str = None
    pgp_account_name :str = None
    export_folder :str = './EXPORT/'
    factory_fn_ls : List[Callable] = field(default_factory = lambda :[export_jupyter_instance_accounts])
    
