const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
let __intlayer_api = require("@intlayer/api");
let __intlayer_chokidar = require("@intlayer/chokidar");
let __intlayer_config = require("@intlayer/config");
let node_path = require("node:path");
let __intlayer_unmerged_dictionaries_entry = require("@intlayer/unmerged-dictionaries-entry");
let __intlayer_core = require("@intlayer/core");

//#region src/fill/translateDictionary.ts
const hasMissingMetadata = (dictionary) => !dictionary.description || !dictionary.title || !dictionary.tags;
const CHUNK_SIZE = 7e3;
const GLOBAL_MAX_RETRY = 2;
const MAX_RETRY = 3;
const RETRY_DELAY = 1e3 * 10;
const translateDictionary = async (task, configuration, options) => {
	const appLogger = (0, __intlayer_config.getAppLogger)(configuration);
	const intlayerAPI = (0, __intlayer_api.getIntlayerAPIProxy)(void 0, configuration);
	const { mode, aiOptions, fillMetadata } = {
		mode: "complete",
		fillMetadata: true,
		...options
	};
	return await (0, __intlayer_config.retryManager)(async () => {
		const baseUnmergedDictionary = (0, __intlayer_unmerged_dictionaries_entry.getUnmergedDictionaries)(configuration)[task.dictionaryKey].find((dict) => dict.localId === task.dictionaryLocalId);
		if (!baseUnmergedDictionary) {
			appLogger(`${task.dictionaryPreset}Dictionary not found in unmergedDictionariesRecord. Skipping.`, { level: "warn" });
			return {
				...task,
				dictionaryOutput: null
			};
		}
		let metadata;
		if (fillMetadata && (hasMissingMetadata(baseUnmergedDictionary) || mode === "review")) {
			const defaultLocaleDictionary = (0, __intlayer_core.getPerLocaleDictionary)(baseUnmergedDictionary, configuration.internationalization.defaultLocale);
			appLogger(`${task.dictionaryPreset} Filling missing metadata for ${(0, __intlayer_config.colorizePath)((0, node_path.basename)(baseUnmergedDictionary.filePath))}`, { level: "info" });
			const runAudit = async () => await intlayerAPI.ai.auditContentDeclarationMetadata({
				fileContent: JSON.stringify(defaultLocaleDictionary),
				aiOptions
			});
			metadata = (options?.onHandle ? await options.onHandle(runAudit) : await runAudit()).data?.fileContent;
		}
		let dictionaryToProcess = baseUnmergedDictionary;
		const translatedContent = {};
		for await (const targetLocale of task.targetLocales) {
			/**
			* In complete mode, for large dictionaries, we want to filter all content that is already translated
			*
			* targetLocale: fr
			*
			* { test1: t({ ar: 'Hello', en: 'Hello', fr: 'Bonjour' } }) -> {}
			* { test2: t({ ar: 'Hello', en: 'Hello' }) } -> { test2: t({ ar: 'Hello', en: 'Hello' }) }
			*
			*/
			if (mode === "complete") dictionaryToProcess = (0, __intlayer_core.getFilterMissingTranslationsDictionary)(dictionaryToProcess, targetLocale);
			dictionaryToProcess = (0, __intlayer_core.getPerLocaleDictionary)(dictionaryToProcess, task.sourceLocale);
			const targetLocaleDictionary = (0, __intlayer_core.getPerLocaleDictionary)(baseUnmergedDictionary, targetLocale);
			const localePreset = (0, __intlayer_config.colon)([
				(0, __intlayer_config.colorize)("[", __intlayer_config.ANSIColors.GREY_DARK),
				(0, __intlayer_chokidar.formatLocale)(targetLocale),
				(0, __intlayer_config.colorize)("]", __intlayer_config.ANSIColors.GREY_DARK)
			].join(""), { colSize: 10 });
			const createChunkPreset = (chunkIndex, totalChunks) => {
				if (totalChunks <= 1) return "";
				return (0, __intlayer_config.colon)([
					(0, __intlayer_config.colorize)("[", __intlayer_config.ANSIColors.GREY_DARK),
					(0, __intlayer_config.colorizeNumber)(chunkIndex + 1),
					(0, __intlayer_config.colorize)(`/${totalChunks}`, __intlayer_config.ANSIColors.GREY_DARK),
					(0, __intlayer_config.colorize)("]", __intlayer_config.ANSIColors.GREY_DARK)
				].join(""), { colSize: 5 });
			};
			appLogger(`${task.dictionaryPreset}${localePreset} Preparing ${(0, __intlayer_config.colorizePath)((0, node_path.basename)(targetLocaleDictionary.filePath))}`, { level: "info" });
			const chunkedJsonContent = (0, __intlayer_chokidar.chunkJSON)(dictionaryToProcess.content, CHUNK_SIZE);
			const nbOfChunks = chunkedJsonContent.length;
			if (nbOfChunks > 1) appLogger(`${task.dictionaryPreset}${localePreset} Split into ${(0, __intlayer_config.colorizeNumber)(nbOfChunks)} chunks for translation`, { level: "info" });
			const chunkResult = [];
			const chunkPromises = chunkedJsonContent.map((chunk) => {
				const chunkPreset = createChunkPreset(chunk.index, chunk.total);
				if (nbOfChunks > 1) appLogger(`${task.dictionaryPreset}${localePreset}${chunkPreset} Translating chunk`, { level: "info" });
				const chunkContent = (0, __intlayer_chokidar.reconstructFromSingleChunk)(chunk);
				const presetOutputContent = (0, __intlayer_chokidar.reduceObjectFormat)(targetLocaleDictionary.content, chunkContent);
				const executeTranslation = async () => {
					return await (0, __intlayer_config.retryManager)(async () => {
						const translationResult = await intlayerAPI.ai.translateJSON({
							entryFileContent: chunkContent,
							presetOutputContent,
							dictionaryDescription: dictionaryToProcess.description ?? metadata?.description ?? "",
							entryLocale: task.sourceLocale,
							outputLocale: targetLocale,
							mode,
							aiOptions
						});
						if (!translationResult.data?.fileContent) throw new Error("No content result");
						const { isIdentic } = (0, __intlayer_chokidar.verifyIdenticObjectFormat)(translationResult.data.fileContent, chunkContent);
						if (!isIdentic) throw new Error("Translation result does not match expected format");
						return translationResult.data.fileContent;
					}, {
						maxRetry: MAX_RETRY,
						delay: RETRY_DELAY,
						onError: ({ error, attempt, maxRetry }) => {
							const chunkPreset$1 = createChunkPreset(chunk.index, chunk.total);
							appLogger(`${task.dictionaryPreset}${localePreset}${chunkPreset$1} ${(0, __intlayer_config.colorize)("Error filling:", __intlayer_config.ANSIColors.RED)} ${(0, __intlayer_config.colorize)(error, __intlayer_config.ANSIColors.GREY_DARK)} - Attempt ${(0, __intlayer_config.colorizeNumber)(attempt + 1)} of ${(0, __intlayer_config.colorizeNumber)(maxRetry)}`, { level: "error" });
						}
					})();
				};
				return (options?.onHandle ? options.onHandle(executeTranslation) : executeTranslation()).then((result) => ({
					chunk,
					result
				}));
			});
			(await Promise.all(chunkPromises)).sort((a, b) => a.chunk.index - b.chunk.index).forEach(({ result }) => {
				chunkResult.push(result);
			});
			translatedContent[targetLocale] = (0, __intlayer_core.mergeDictionaries)(chunkResult.map((chunk) => ({
				...dictionaryToProcess,
				content: chunk
			}))).content;
		}
		let dictionaryOutput = {
			...baseUnmergedDictionary,
			...metadata
		};
		for (const targetLocale of task.targetLocales) if (translatedContent[targetLocale]) dictionaryOutput = (0, __intlayer_core.insertContentInDictionary)(dictionaryOutput, translatedContent[targetLocale], targetLocale);
		appLogger(`${task.dictionaryPreset} ${(0, __intlayer_config.colorize)("Translation completed successfully", __intlayer_config.ANSIColors.GREEN)} for ${(0, __intlayer_config.colorizePath)((0, node_path.basename)(dictionaryOutput.filePath))}`, { level: "info" });
		return {
			...task,
			dictionaryOutput
		};
	}, {
		maxRetry: GLOBAL_MAX_RETRY,
		delay: RETRY_DELAY,
		onError: ({ error, attempt, maxRetry }) => {
			appLogger(`${task.dictionaryPreset} ${(0, __intlayer_config.colorize)("Error fill command:", __intlayer_config.ANSIColors.RED)} ${(0, __intlayer_config.colorize)(error, __intlayer_config.ANSIColors.GREY_DARK)} - Attempt ${(0, __intlayer_config.colorizeNumber)(attempt + 1)} of ${(0, __intlayer_config.colorizeNumber)(maxRetry)}`, { level: "error" });
		},
		onMaxTryReached: ({ error }) => {
			appLogger(`${task.dictionaryPreset} ${(0, __intlayer_config.colorize)("Maximum number of retries reached:", __intlayer_config.ANSIColors.RED)} ${(0, __intlayer_config.colorize)(error, __intlayer_config.ANSIColors.GREY_DARK)}`, { level: "error" });
		}
	})();
};

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