const require_rolldown_runtime = require('../../../../../_virtual/rolldown_runtime.cjs');
const require_logger = require('../../../../config/dist/esm/logger.cjs');
const require_retryManager = require('../../../../config/dist/esm/retryManager.cjs');
const require_formatter = require('../chokidar/dist/esm/utils/formatter.cjs');
const require_index = require('../unmerged-dictionaries-entry/dist/esm/index.cjs');
const require_proxy = require('../api/dist/esm/proxy.cjs');
const require_chunkJSON = require('../chokidar/dist/esm/utils/chunkJSON.cjs');
const require_reduceObjectFormat = require('../chokidar/dist/esm/utils/reduceObjectFormat.cjs');
const require_verifyIdenticObjectFormat = require('../chokidar/dist/esm/utils/verifyIdenticObjectFormat.cjs');
const require_getFilterMissingTranslationsContent = require('../core/dist/esm/deepTransformPlugins/getFilterMissingTranslationsContent.cjs');
const require_getLocalizedContent = require('../core/dist/esm/deepTransformPlugins/getLocalizedContent.cjs');
const require_insertContentInDictionary = require('../core/dist/esm/deepTransformPlugins/insertContentInDictionary.cjs');
const require_mergeDictionaries = require('../core/dist/esm/dictionaryManipulator/mergeDictionaries.cjs');
let node_path = require("node:path");

//#region ../@intlayer/cli/dist/esm/fill/translateDictionary.mjs
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 = require_logger.getAppLogger(configuration);
	const intlayerAPI = require_proxy.getIntlayerAPIProxy(void 0, configuration);
	const { mode, aiOptions, fillMetadata } = {
		mode: "complete",
		fillMetadata: true,
		...options
	};
	return await require_retryManager.retryManager(async () => {
		const baseUnmergedDictionary = require_index.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 = require_getLocalizedContent.getPerLocaleDictionary(baseUnmergedDictionary, configuration.internationalization.defaultLocale);
			appLogger(`${task.dictionaryPreset} Filling missing metadata for ${require_logger.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 = require_getFilterMissingTranslationsContent.getFilterMissingTranslationsDictionary(dictionaryToProcess, targetLocale);
			dictionaryToProcess = require_getLocalizedContent.getPerLocaleDictionary(dictionaryToProcess, task.sourceLocale);
			const targetLocaleDictionary = require_getLocalizedContent.getPerLocaleDictionary(baseUnmergedDictionary, targetLocale);
			const localePreset = require_logger.colon([
				require_logger.colorize("[", require_logger.ANSIColors.GREY_DARK),
				require_formatter.formatLocale(targetLocale),
				require_logger.colorize("]", require_logger.ANSIColors.GREY_DARK)
			].join(""), { colSize: 10 });
			const createChunkPreset = (chunkIndex, totalChunks) => {
				if (totalChunks <= 1) return "";
				return require_logger.colon([
					require_logger.colorize("[", require_logger.ANSIColors.GREY_DARK),
					require_logger.colorizeNumber(chunkIndex + 1),
					require_logger.colorize(`/${totalChunks}`, require_logger.ANSIColors.GREY_DARK),
					require_logger.colorize("]", require_logger.ANSIColors.GREY_DARK)
				].join(""), { colSize: 5 });
			};
			appLogger(`${task.dictionaryPreset}${localePreset} Preparing ${require_logger.colorizePath((0, node_path.basename)(targetLocaleDictionary.filePath))}`, { level: "info" });
			const chunkedJsonContent = require_chunkJSON.chunkJSON(dictionaryToProcess.content, CHUNK_SIZE);
			const nbOfChunks = chunkedJsonContent.length;
			if (nbOfChunks > 1) appLogger(`${task.dictionaryPreset}${localePreset} Split into ${require_logger.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 = require_chunkJSON.reconstructFromSingleChunk(chunk);
				const presetOutputContent = require_reduceObjectFormat.reduceObjectFormat(targetLocaleDictionary.content, chunkContent);
				const executeTranslation = async () => {
					return await require_retryManager.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 } = require_verifyIdenticObjectFormat.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} ${require_logger.colorize("Error filling:", require_logger.ANSIColors.RED)} ${require_logger.colorize(error, require_logger.ANSIColors.GREY_DARK)} - Attempt ${require_logger.colorizeNumber(attempt + 1)} of ${require_logger.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] = require_mergeDictionaries.mergeDictionaries(chunkResult.map((chunk) => ({
				...dictionaryToProcess,
				content: chunk
			}))).content;
		}
		let dictionaryOutput = {
			...baseUnmergedDictionary,
			...metadata
		};
		for (const targetLocale of task.targetLocales) if (translatedContent[targetLocale]) dictionaryOutput = require_insertContentInDictionary.insertContentInDictionary(dictionaryOutput, translatedContent[targetLocale], targetLocale);
		appLogger(`${task.dictionaryPreset} ${require_logger.colorize("Translation completed successfully", require_logger.ANSIColors.GREEN)} for ${require_logger.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} ${require_logger.colorize("Error fill command:", require_logger.ANSIColors.RED)} ${require_logger.colorize(error, require_logger.ANSIColors.GREY_DARK)} - Attempt ${require_logger.colorizeNumber(attempt + 1)} of ${require_logger.colorizeNumber(maxRetry)}`, { level: "error" });
		},
		onMaxTryReached: ({ error }) => {
			appLogger(`${task.dictionaryPreset} ${require_logger.colorize("Maximum number of retries reached:", require_logger.ANSIColors.RED)} ${require_logger.colorize(error, require_logger.ANSIColors.GREY_DARK)}`, { level: "error" });
		}
	})();
};

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