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

//#region ../@intlayer/webpack/dist/esm/chokidar/dist/esm/buildIntlayerDictionary/writeRemoteDictionary.mjs
/**
* Write the localized dictionaries to the dictionariesDir
* @param mergedDictionaries - The merged dictionaries
* @param configuration - The configuration
* @returns The final dictionaries
*
* @example
* ```ts
* const unmergedDictionaries = await writeUnmergedDictionaries(dictionaries);
* const finalDictionaries = await writeFinalDictionaries(unmergedDictionaries);
* console.log(finalDictionaries);
*
* // .intlayer/fetch_dictionaries/home.json
* // { key: 'home', content: { ... } },
* ```
*/
const writeRemoteDictionary = async (remoteDictionaries, configuration = getConfiguration()) => {
	const { remoteDictionariesDir } = configuration.content;
	await mkdir(resolve(remoteDictionariesDir), { recursive: true });
	const groupedDictionaries = groupDictionariesByKey(filterInvalidDictionaries(remoteDictionaries, configuration));
	const results = await parallelize(Object.entries(groupedDictionaries), async ([key, dictionaries]) => {
		if (key === "undefined") return;
		const orderedDictionaries = orderDictionaries(formatDistantDictionaries(dictionaries), configuration);
		const unmergedFilePath = resolve(remoteDictionariesDir, `${key}.json`);
		await writeJsonIfChanged(unmergedFilePath, orderedDictionaries).catch((err) => {
			console.error(`${x} Error creating unmerged ${colorizePath(unmergedFilePath)}:`, err);
		});
		return [key, {
			dictionaryPath: unmergedFilePath,
			dictionaries
		}];
	});
	return Object.fromEntries(results.filter(Boolean));
};

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