module.exports = (opts, envKey) => {
	const
		fs = require('fs'),
		path = require('path'),

		json5 = require('json5'),

		{ convertCamelToUpperSnakeCase, readJsonIfExists } = require('./utils'),

		{ cwd, env } = process,

		def = readJsonIfExists(path.resolve(__dirname, 'defaults.json5')),

		// gets value from ENV || options || defaults (in that order)
		getVal = (envName) => {
			const snakeEnvName = `${envKey}_${convertCamelToUpperSnakeCase(envName)}`;
			if (env[snakeEnvName]) return env[snakeEnvName];
			if (opts[envName]) return opts[envName];
			return def[envName];
		},

		// gets array from ENV || options || defaults (in that order)
		getArray = (envName, optName = '') => {
			if (optName === '') {
				optName = envName;
				envName = convertCamelToUpperSnakeCase(envName);
			}
			envName = `${envKey}_${envName}`;
			if (env[envName]) return env[envName].split(path.delimiter);
			if (Array.isArray(opts[optName]) && opts[optName].length) return opts[optName];
			return def[optName];
		};

		
	return {

		...Object.keys(def).reduce((acc, curr) => {
			if (Array.isArray(def[curr])) acc[curr] = getArray(curr);
			else acc[curr] = getVal(curr);
			return acc;
		}, {}),
	};
};
