from rampwf.utils.importing import import_module_from_source
import os
from time import gmtime, strftime
import json


def load_system_env(pass_system_env_object=False):
    env_module_path = 'env.py'
    env_module = import_module_from_source(env_module_path, 'env')
    system_env_object = env_module.Env
    system_env = system_env_object()
    if pass_system_env_object:
        return system_env, system_env_object
    else:
        return system_env


def save_experiment_metadata(output_dir, metadata, agent_name, submission):
    output_data_path = os.path.join(output_dir, 'data')
    if not os.path.exists(output_data_path):
        os.mkdir(output_data_path)

    if os.path.exists(os.path.join(output_data_path, 'metadata.json')):
        with open(os.path.join(output_data_path, 'metadata.json'), "r") as json_file:
            metadata = json.load(json_file)

    current_date = strftime("%Y-%m-%d %H:%M:%S", gmtime())
    metadata[f"date_experiment_{submission}_{agent_name}"] = current_date

    with open(os.path.join(output_data_path, 'metadata.json'), 'w') as outfile:
        json.dump(metadata, outfile, indent=4)

