import prefect
from datamonk.utils import functions as utils
from datamonk.scriptorium.process import monitoring
import datamonk.scriptorium.apps.dataform as dataform
import os
import logging
import shutil
@prefect.task
def dataform_transform(project_id=os.environ.get("DATAFORM_PROJECT_ID"),
                       token=os.environ.get("DATAFORM_API_KEY"),
                       schedule=os.environ.get("DATAFORM_SCHEDULE_NAME")
                       ):
       df_inst=dataform.instance(project_id=project_id,
                                 token=token)
       return df_inst.run(schedule=schedule)


@prefect.task
def data_monitoring(config):
    return monitoring.run(rules_list=config["rules"])

def prefect_parameter_read_json(path,param_name):
        return prefect.Parameter(param_name,
                                 default=utils.local.read_configJSON(path,"dict")
                                 )


@prefect.task
def generate_time_range(start,end,output_format='%Y-%m-%dT%H:%M:%S'):
    logger = logging.getLogger(__name__)
    generated_time_range = utils.time(output_format=output_format).get_time_range(start=start,end=end)

    logger.info(f"generated_time_range{generated_time_range}")
    return generated_time_range

@prefect.task
def pull_dbt_repo(git_token_name,
                  repository_path,
                  repository_server,
                  branch='',
                  folder_name='dbt_project'):
    from prefect.client import Secret
    import pygit2

    logger = prefect.context.get("logger")
    shutil.rmtree("dbt",
                  ignore_errors=True
                  )  # Delete folder on run

    git_token = Secret(git_token_name).get()
    branch = '#'+branch if branch != '' else branch
    dbt_repo = (
        f"https://prefect:{git_token}@{repository_server}/{repository_path}.git{branch}"
    )

    pygit2.clone_repository(dbt_repo, folder_name)


@prefect.task(trigger=prefect.triggers.all_finished)
def output_print(output):
    logger = prefect.context.get("logger")
    for o in output:
        logger.info(o)