from json import load
from os import path

from pycs.interfaces.Pipeline import Pipeline


def load_from_root_folder(root_folder: str) -> Pipeline:
    """
    load configuration.json and create an instance from the included code object

    :param root_folder: path to model root folder
    :return: Pipeline instance
    """
    # load configuration.json
    configuration_path = path.join(root_folder, 'configuration.json')
    with open(configuration_path, 'r') as configuration_file:
        configuration = load(configuration_file)

    # load code
    code_path = path.join(root_folder, configuration['code']['module'])
    module_name = code_path.replace('/', '.').replace('\\', '.')
    class_name = configuration['code']['class']

    imported_module = __import__(module_name, fromlist=[class_name])
    class_attr = getattr(imported_module, class_name)

    # return instance
    return class_attr(root_folder, configuration)
