import { parallelize } from "../utils/parallelize.mjs";
import { writeJsonIfChanged } from "../writeJsonIfChanged.mjs";
import { mergeDictionaries } from "../core/dist/esm/dictionaryManipulator/mergeDictionaries.mjs";
import { normalizeDictionaries } from "../core/dist/esm/dictionaryManipulator/normalizeDictionary.mjs";
import { resolve } from "node:path";
import { mkdir } from "node:fs/promises";
import { colorizePath, getConfiguration } from "@intlayer/config";

//#region ../@intlayer/webpack/dist/esm/chokidar/dist/esm/buildIntlayerDictionary/writeMergedDictionary.mjs
/**
* Write the merged dictionaries to the dictionariesDir
* @param groupedDictionaries - The grouped dictionaries
* @param configuration - The configuration
* @returns The merged dictionaries
*
* @example
* ```ts
* const unmergedDictionaries = await writeUnmergedDictionaries(dictionaries);
* const finalDictionaries = await writeFinalDictionaries(unmergedDictionaries);
* console.log(finalDictionaries);
*
* // .intlayer/dictionary/home.json
* // { key: 'home', content: { ... } },
* ```
*/
const writeMergedDictionaries = async (groupedDictionaries, configuration = getConfiguration()) => {
	const { dictionariesDir } = configuration.content;
	await mkdir(resolve(dictionariesDir), { recursive: true });
	const results = await parallelize(Object.entries(groupedDictionaries), async ([key, dictionariesEntry]) => {
		if (key === "undefined") return;
		const mergedDictionary = mergeDictionaries(normalizeDictionaries(dictionariesEntry.dictionaries, configuration));
		const resultFilePath = resolve(dictionariesDir, `${key}.json`);
		await writeJsonIfChanged(resultFilePath, mergedDictionary).catch((err) => {
			console.error(`Error creating merged ${colorizePath(resultFilePath)}:`, err);
		});
		return [key, {
			dictionaryPath: resultFilePath,
			dictionary: mergedDictionary
		}];
	});
	return Object.fromEntries(results.filter(Boolean));
};

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