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

//#region ../chokidar/dist/esm/buildIntlayerDictionary/writeUnmergedDictionary.mjs
const groupDictionariesByKey = (dictionaries) => dictionaries.reduce((acc, dictionary) => {
	const key = dictionary.key;
	if (!acc[key]) acc[key] = [];
	acc[key].push(dictionary);
	return acc;
}, {});
/**
* Write the unmerged dictionaries to the unmergedDictionariesDir
* @param dictionaries - The dictionaries to write
* @param configuration - The configuration
* @returns The grouped dictionaries
*
* @example
* ```ts
* const unmergedDictionaries = await writeUnmergedDictionaries(dictionaries);
* console.log(unmergedDictionaries);
*
* // .intlayer/unmerged_dictionaries/home.json
* // {
* //   [
* //     { key: 'home', content: { ... } },
* //     { key: 'home', content: { ... } },
* //   ],
* // }
* ```
*/
const writeUnmergedDictionaries = async (dictionaries, configuration) => {
	const { unmergedDictionariesDir } = configuration.content;
	await mkdir(resolve(unmergedDictionariesDir), { recursive: true });
	const groupedDictionaries = groupDictionariesByKey(filterInvalidDictionaries(dictionaries, configuration));
	const results = await parallelize(Object.entries(groupedDictionaries), async ([key, dictionaries$1]) => {
		if (key === "undefined") return;
		const orderedDictionaries = orderDictionaries(dictionaries$1, configuration);
		const unmergedFilePath = resolve(unmergedDictionariesDir, `${key}.json`);
		await writeJsonIfChanged(unmergedFilePath, orderedDictionaries).catch((err) => {
			console.error(`${x} Error creating unmerged ${colorizePath(unmergedFilePath)}:`, err);
		});
		return [key, {
			dictionaryPath: unmergedFilePath,
			dictionaries: dictionaries$1
		}];
	});
	return Object.fromEntries(results.filter(Boolean));
};

//#endregion
export { groupDictionariesByKey, writeUnmergedDictionaries };
//# sourceMappingURL=writeUnmergedDictionary.mjs.map