"""
DMM Recipe runner
"""

# Imports
import importlib
import sys
import yaml
from loguru import logger

# Initialize logger
logger.add(sys.stderr, format="{time} {level} {message}", filter="my_module", level="INFO")
logger.add("out.log", backtrace=True, diagnose=True)

@logger.catch
def read_recipe(recipe):
    """
    Read the list of stuff that we should be doing.
    """
    logger.info("Reading recipe: " + recipe)
    configfile = open(recipe, "r")
    global config
    config = (yaml.safe_load(configfile))
    logger.debug("Config:\n" + str(config))
    sys.path.append(config['module_path'])
    logger.debug("Add-on module path(s): ", config['module_path'])
    return list(config['recipe'])


@logger.catch
def perform_recipe(recipe):
    """
    Runs through the tasks in our recipe.
    """
    for task in read_recipe(recipe):
        run_task(task)
    logger.info("Recipe: %s has completed." % recipe)


@logger.catch
def get_task_config(task):
    """
    Returns configuration for a module.
    """
    return config['recipe'][task]


@logger.catch
def run_task(task):
    """
    Run through a task in a recipe.

    We load a module as needed and then unload it when we're done
    to conserve memory for installer environments.
    """
    logger.info("Running task: " + task)
    module_name = config['recipe'][task]['module']
    globals()[module_name] = importlib.import_module("dmm.modules." + module_name + "." + module_name)
    task_config = get_task_config(task)
    logger.debug("Task details: " + str(task_config))
    #try:
    eval(module_name).recipe_run(task_config, config['global_settings'])
    #except:
    #    logger.error("An error has occured!")
    #    #sys.exit()
    del globals()[module_name]

logger.debug("DMM Recipe reader loaded")

