import { parallelize } from "../utils/parallelize.mjs";
import { getPerLocaleDictionary } from "../core/dist/esm/deepTransformPlugins/getLocalizedContent.mjs";
import { writeFileIfChanged } from "../writeFileIfChanged.mjs";
import { writeJsonIfChanged } from "../writeJsonIfChanged.mjs";
import { relative, resolve } from "node:path";
import { mkdir } from "node:fs/promises";
import { colorizePath, getConfiguration, normalizePath } from "@intlayer/config";

//#region ../@intlayer/chokidar/dist/esm/buildIntlayerDictionary/writeDynamicDictionary.mjs
/**
* This function generates the content of the dictionary list file
*/
const generateDictionaryEntryPoint = (localizedDictionariesPathsRecord, format = "esm", configuration = 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 = normalizePath(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 = getConfiguration(), formats = ["cjs", "esm"]) => {
	const { locales, defaultLocale } = configuration.internationalization;
	const { dynamicDictionariesDir } = configuration.content;
	await mkdir(resolve(dynamicDictionariesDir), { recursive: true });
	const resultDictionariesPaths = {};
	await parallelize(Object.entries(mergedDictionaries).sort(([a], [b]) => String(a).localeCompare(String(b))), async ([key, dictionaryEntry]) => {
		if (key === "undefined") return;
		const localizedDictionariesPathsRecord = {};
		await parallelize(locales, async (locale) => {
			const localizedDictionary = getPerLocaleDictionary(dictionaryEntry.dictionary, locale, defaultLocale);
			const outputFileName = `${key}.${locale}.json`;
			const resultFilePath = resolve(dynamicDictionariesDir, outputFileName);
			await writeJsonIfChanged(resultFilePath, localizedDictionary).catch((err) => {
				console.error(`Error creating localized ${outputFileName}:`, err);
			});
			localizedDictionariesPathsRecord[locale] = {
				dictionaryPath: resultFilePath,
				dictionary: localizedDictionary
			};
		});
		resultDictionariesPaths[key] = localizedDictionariesPathsRecord;
		await parallelize(formats, async (format) => {
			const extension = format === "cjs" ? "cjs" : "mjs";
			const content = generateDictionaryEntryPoint(localizedDictionariesPathsRecord, format, configuration);
			await writeFileIfChanged(resolve(dynamicDictionariesDir, `${key}.${extension}`), content).catch((err) => {
				console.error(`Error creating dynamic ${colorizePath(resolve(dynamicDictionariesDir, `${key}.${extension}`))}:`, err);
			});
		});
	});
	return resultDictionariesPaths;
};

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