import { logger } from "../logger.mjs";
import { cache } from "../utils/cache.mjs";
import { getPackageJsonPath } from "../utils/getPackageJsonPath.mjs";
import { buildConfigurationFields } from "./buildConfigurationFields.mjs";
import { searchConfigurationFile } from "./searchConfigurationFile.mjs";
import { loadConfigurationFile } from "./loadConfigurationFile.mjs";
import { relative } from "node:path";
import merge from "deepmerge";

//#region ../@intlayer/cli/dist/esm/dictionaries-entry/dist/esm/config/dist/esm/configFile/getConfiguration.mjs
/**
* Get the configuration for the intlayer by reading the configuration file (e.g. intlayer.config.js)
*/
const getConfigurationAndFilePath = (options) => {
	let baseDir;
	try {
		baseDir = options?.baseDir ?? getPackageJsonPath().baseDir;
	} catch (_err) {
		return {
			configuration: buildConfigurationFields({}, options?.baseDir, options?.logFunctions),
			configurationFilePath: void 0
		};
	}
	const cachedConfiguration = cache.get(options);
	if (cachedConfiguration) return cachedConfiguration;
	const { configurationFilePath, numCustomConfiguration } = searchConfigurationFile(baseDir);
	if (options?.override?.log?.mode === "verbose") logConfigFileResult(baseDir, numCustomConfiguration, configurationFilePath);
	let storedConfiguration;
	if (configurationFilePath) storedConfiguration = buildConfigurationFields(loadConfigurationFile(configurationFilePath, {
		projectRequire: options?.require,
		envVarOptions: {
			env: options?.env,
			envFile: options?.envFile
		},
		additionalEnvVars: options?.additionalEnvVars,
		aliases: options?.aliases
	}), options?.baseDir, options?.logFunctions);
	const projectRequireConfig = options?.require ? { build: {
		require: options?.require,
		cache: options?.cache
	} } : {};
	const configuration = merge(merge(storedConfiguration ?? {}, projectRequireConfig), options?.override ?? {});
	cache.set(options, {
		configuration,
		configurationFilePath
	});
	return {
		configuration,
		configurationFilePath
	};
};
/**
* Get the configuration for the intlayer by reading the configuration file (e.g. intlayer.config.js)
*/
const getConfiguration = (options) => getConfigurationAndFilePath(options).configuration;
const logConfigFileResult = (baseDir, numCustomConfiguration, configurationFilePath) => {
	if (numCustomConfiguration === 0) logger("Configuration file not found, using default configuration.", { isVerbose: true });
	else {
		const relativeOutputPath = relative(baseDir, configurationFilePath);
		if (numCustomConfiguration === 1) logger(`Configuration file found: ${relativeOutputPath}.`, { isVerbose: true });
		else logger(`Multiple configuration files found, using ${relativeOutputPath}.`, { isVerbose: true });
	}
};

//#endregion
export { getConfiguration };
//# sourceMappingURL=getConfiguration.mjs.map