const require_rolldown_runtime = require('../../../../_virtual/rolldown_runtime.cjs');
const require_logger = require('../../../../config/dist/esm/logger.cjs');
const require_normalizePath = require('../../../../config/dist/esm/utils/normalizePath.cjs');
const require_getConfiguration = require('../../../../config/dist/esm/configFile/getConfiguration.cjs');
const require_parallelize = require('../utils/parallelize.cjs');
const require_getLocalizedContent = require('../core/dist/esm/deepTransformPlugins/getLocalizedContent.cjs');
const require_writeFileIfChanged = require('../writeFileIfChanged.cjs');
const require_writeJsonIfChanged = require('../writeJsonIfChanged.cjs');
let node_path = require("node:path");
let node_fs_promises = require("node:fs/promises");

//#region ../chokidar/dist/esm/buildIntlayerDictionary/writeDynamicDictionary.mjs
/**
* This function generates the content of the dictionary list file
*/
const generateDictionaryEntryPoint = (localizedDictionariesPathsRecord, format = "esm", configuration = require_getConfiguration.getConfiguration()) => {
	const { dynamicDictionariesDir } = configuration.content;
	let content = "";
	const formattedDictionaryMap = Object.entries(localizedDictionariesPathsRecord).filter((entry) => Boolean(entry[1])).sort(([a], [b]) => String(a).localeCompare(String(b))).map(([locale, dictionary]) => {
		const relativePath = require_normalizePath.normalizePath((0, node_path.relative)(dynamicDictionariesDir, dictionary.dictionaryPath));
		if (format === "esm") return `  '${locale}': () => import('./${relativePath}', { assert: { type: 'json' }}).then(mod => mod.default)`;
		return `  '${locale}': () => Promise.resolve(require('./${relativePath}'))`;
	}).join(",\n");
	content += `const content = {\n${formattedDictionaryMap}\n};\n`;
	if (format === "esm") content += `export default content;\n`;
	if (format === "cjs") content += `module.exports = content;\n`;
	return content;
};
/**
* 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/dynamic_dictionaries/home.json
* // { key: 'home', content: { ... } },
* ```
*/
const writeDynamicDictionary = async (mergedDictionaries, configuration = require_getConfiguration.getConfiguration(), formats = ["cjs", "esm"]) => {
	const { locales, defaultLocale } = configuration.internationalization;
	const { dynamicDictionariesDir } = configuration.content;
	await (0, node_fs_promises.mkdir)((0, node_path.resolve)(dynamicDictionariesDir), { recursive: true });
	const resultDictionariesPaths = {};
	await require_parallelize.parallelize(Object.entries(mergedDictionaries).sort(([a], [b]) => String(a).localeCompare(String(b))), async ([key, dictionaryEntry]) => {
		if (key === "undefined") return;
		const localizedDictionariesPathsRecord = {};
		await require_parallelize.parallelize(locales, async (locale) => {
			const localizedDictionary = require_getLocalizedContent.getPerLocaleDictionary(dictionaryEntry.dictionary, locale, defaultLocale);
			const outputFileName = `${key}.${locale}.json`;
			const resultFilePath = (0, node_path.resolve)(dynamicDictionariesDir, outputFileName);
			await require_writeJsonIfChanged.writeJsonIfChanged(resultFilePath, localizedDictionary).catch((err) => {
				console.error(`Error creating localized ${outputFileName}:`, err);
			});
			localizedDictionariesPathsRecord[locale] = {
				dictionaryPath: resultFilePath,
				dictionary: localizedDictionary
			};
		});
		resultDictionariesPaths[key] = localizedDictionariesPathsRecord;
		await require_parallelize.parallelize(formats, async (format) => {
			const extension = format === "cjs" ? "cjs" : "mjs";
			const content = generateDictionaryEntryPoint(localizedDictionariesPathsRecord, format, configuration);
			await require_writeFileIfChanged.writeFileIfChanged((0, node_path.resolve)(dynamicDictionariesDir, `${key}.${extension}`), content).catch((err) => {
				console.error(`Error creating dynamic ${require_logger.colorizePath((0, node_path.resolve)(dynamicDictionariesDir, `${key}.${extension}`))}:`, err);
			});
		});
	});
	return resultDictionariesPaths;
};

//#endregion
exports.writeDynamicDictionary = writeDynamicDictionary;
//# sourceMappingURL=writeDynamicDictionary.cjs.map