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

//#region ../@intlayer/cli/dist/esm/chokidar/dist/esm/buildIntlayerDictionary/writeFetchDictionary.mjs
/**
* This function generates the content of the dictionary list file
*/
const generateDictionaryEntryPoint = (localedDictionariesPathsRecord, format = "esm", configuration = require_getConfiguration.getConfiguration()) => {
	const { fetchDictionariesDir } = configuration.content;
	const { liveSyncURL } = configuration.editor;
	let content = "";
	const formattedDictionaryMap = Object.entries(localedDictionariesPathsRecord).map(([locale, dictionary]) => {
		const relativePath = require_normalizePath.normalizePath((0, node_path.relative)(fetchDictionariesDir, dictionary.dictionaryPath));
		if (format === "esm") return `  '${locale}': () => (async () => { try {return await fetch('${liveSyncURL}/dictionaries/${dictionary.dictionary.key}/${locale}').then(res => res.json())} catch (_error) {return await import('./${relativePath}', { assert: { type: 'json' }}).then(mod => mod.default)}})()`;
		return `  '${locale}': () => (async () => { try {return await fetch('${liveSyncURL}/dictionaries/${dictionary.dictionary.key}/${locale}').then(res => res.json())} catch (_error) {return 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/fetch_dictionaries/home.json
* // { key: 'home', content: { ... } },
* ```
*/
const writeFetchDictionary = async (dynamicDictionaries, configuration = require_getConfiguration.getConfiguration(), formats = ["cjs", "esm"]) => {
	const { fetchDictionariesDir } = configuration.content;
	await (0, node_fs_promises.mkdir)((0, node_path.resolve)(fetchDictionariesDir), { recursive: true });
	const resultDictionariesPaths = {};
	await require_parallelize.parallelize(Object.entries(dynamicDictionaries), async ([key, localedDictionariesPathsRecord]) => {
		if (key === "undefined") return;
		await require_parallelize.parallelize(formats, async (format) => {
			const extension = format === "cjs" ? "cjs" : "mjs";
			const content = generateDictionaryEntryPoint(localedDictionariesPathsRecord, format, configuration);
			await require_writeFileIfChanged.writeFileIfChanged((0, node_path.resolve)(fetchDictionariesDir, `${key}.${extension}`), content).catch((err) => {
				console.error(`Error creating fetch ${require_logger.colorizePath((0, node_path.resolve)(fetchDictionariesDir, `${key}.${extension}`))}:`, err);
			});
		});
	});
	return resultDictionariesPaths;
};

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