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_getConfiguration = require('../../../config/dist/esm/configFile/getConfiguration.cjs');
const require_formatter = require('./chokidar/dist/esm/utils/formatter.cjs');
const require_parallelize = require('./chokidar/dist/esm/utils/parallelize.cjs');
const require_listGitFiles = require('./chokidar/dist/esm/listGitFiles.cjs');
const require_checkAccess = require('./utils/checkAccess.cjs');
const require_getChunk = require('./chokidar/dist/esm/utils/getChunk.cjs');
const require__utils_asset = require('./_virtual/_utils_asset.cjs');
const require_chunkInference = require('./utils/chunkInference.cjs');
const require_fixChunkStartEndChars = require('./utils/fixChunkStartEndChars.cjs');
const require_checkFileModifiedRange = require('./utils/checkFileModifiedRange.cjs');
const require_getOutputFilePath = require('./utils/getOutputFilePath.cjs');
const require_calculateChunks = require('./utils/calculateChunks.cjs');
let node_path = require("node:path");
let node_fs_promises = require("node:fs/promises");
let node_fs = require("node:fs");
let fast_glob = require("fast-glob");
fast_glob = require_rolldown_runtime.__toESM(fast_glob);

//#region ../@intlayer/cli/dist/esm/translateDoc.mjs
/**
* Translate a single file for a given locale
*/
const translateFile = async (baseFilePath, outputFilePath, locale, baseLocale, configuration, aiOptions, customInstructions) => {
	try {
		const appLogger = require_logger.getAppLogger(configuration, { config: { prefix: "" } });
		const fileContent = await (0, node_fs_promises.readFile)(baseFilePath, "utf-8");
		let fileResultContent = fileContent;
		const basePrompt = require__utils_asset.readAsset("./prompts/TRANSLATE_PROMPT.md", "utf-8").replaceAll("{{localeName}}", `${require_formatter.formatLocale(locale, false)}`).replaceAll("{{baseLocaleName}}", `${require_formatter.formatLocale(baseLocale, false)}`).replace("{{applicationContext}}", aiOptions?.applicationContext ?? "-").replace("{{customInstructions}}", customInstructions ?? "-");
		const filePrefix = [require_logger.colon(`${require_logger.ANSIColors.GREY_DARK}[${require_formatter.formatPath(baseFilePath)}${require_logger.ANSIColors.GREY_DARK}] `, { colSize: 40 }), `→ ${require_logger.ANSIColors.RESET}`].join("");
		const prefix = [require_logger.colon(`${require_logger.ANSIColors.GREY_DARK}[${require_formatter.formatPath(baseFilePath)}${require_logger.ANSIColors.GREY_DARK}][${require_formatter.formatLocale(locale)}${require_logger.ANSIColors.GREY_DARK}] `, { colSize: 40 }), `→ ${require_logger.ANSIColors.RESET}`].join("");
		const chunks = require_calculateChunks.chunkText(fileContent);
		appLogger(`${filePrefix}Base file splitted into ${require_logger.colorizeNumber(chunks.length)} chunks`);
		for await (const [i, chunk] of chunks.entries()) {
			const isFirstChunk = i === 0;
			const getPrevChunkPrompt = () => `**CHUNK ${i} of ${chunks.length}** that has been translated in ${require_formatter.formatLocale(locale)}:\n///chunkStart///` + require_getChunk.getChunk(fileResultContent, chunks[i - 1]) + `///chunkEnd///`;
			const getBaseChunkContextPrompt = () => `**CHUNK ${i + 1} to ${Math.min(i + 3, chunks.length)} of ${chunks.length}** is the base chunk in ${require_formatter.formatLocale(baseLocale, false)} as reference.\n///chunksStart///` + (chunks[i - 1]?.content ?? "") + chunks[i].content + (chunks[i + 1]?.content ?? "") + `///chunksEnd///`;
			const fileToTranslateCurrentChunk = chunk.content;
			const chunkTranslation = await require_retryManager.retryManager(async () => {
				const result = await require_chunkInference.chunkInference([
					{
						role: "system",
						content: basePrompt
					},
					{
						role: "system",
						content: getBaseChunkContextPrompt()
					},
					...isFirstChunk ? [] : [{
						role: "system",
						content: getPrevChunkPrompt()
					}],
					{
						role: "system",
						content: `The next user message will be the **CHUNK ${require_logger.colorizeNumber(i + 1)} of ${require_logger.colorizeNumber(chunks.length)}** in ${require_formatter.formatLocale(baseLocale, false)} to translate in ${require_formatter.formatLocale(locale, false)}:`
					},
					{
						role: "user",
						content: fileToTranslateCurrentChunk
					}
				], aiOptions, configuration);
				appLogger([
					`${prefix}`,
					`${require_logger.ANSIColors.GREY_DARK}[Chunk `,
					require_logger.colorizeNumber(i + 1),
					`${require_logger.ANSIColors.GREY_DARK} of `,
					require_logger.colorizeNumber(chunks.length),
					`${require_logger.ANSIColors.GREY_DARK}] →${require_logger.ANSIColors.RESET} `,
					`${require_logger.colorizeNumber(result.tokenUsed)} tokens used`
				].join(""));
				return require_fixChunkStartEndChars.fixChunkStartEndChars(result?.fileContent, fileToTranslateCurrentChunk);
			})();
			fileResultContent = fileResultContent.replace(fileToTranslateCurrentChunk, chunkTranslation);
		}
		(0, node_fs.mkdirSync)((0, node_path.dirname)(outputFilePath), { recursive: true });
		(0, node_fs.writeFileSync)(outputFilePath, fileResultContent);
		const relativePath = (0, node_path.relative)(configuration.content.baseDir, outputFilePath);
		appLogger(`${require_logger.colorize("✔", require_logger.ANSIColors.GREEN)} File ${require_formatter.formatPath(relativePath)} created/updated successfully.`);
	} catch (error) {
		console.error(error);
	}
};
/**
* Main translate function: scans all .md files in "en/" (unless you specified DOC_LIST),
* then translates them to each locale in LOCALE_LIST.
*/
const translateDoc = async ({ docPattern, locales, excludedGlobPattern, baseLocale, aiOptions, nbSimultaneousFileProcessed, configOptions, customInstructions, skipIfModifiedBefore, skipIfModifiedAfter, skipIfExists, gitOptions }) => {
	const configuration = require_getConfiguration.getConfiguration(configOptions);
	const appLogger = require_logger.getAppLogger(configuration);
	if (nbSimultaneousFileProcessed && nbSimultaneousFileProcessed > 10) {
		appLogger(`Warning: nbSimultaneousFileProcessed is set to ${nbSimultaneousFileProcessed}, which is greater than 10. Setting it to 10.`);
		nbSimultaneousFileProcessed = 10;
	}
	let docList = await (0, fast_glob.default)(docPattern, { ignore: excludedGlobPattern });
	if (!await require_checkAccess.checkAIAccess(configuration, aiOptions)) return;
	if (gitOptions) {
		const gitChangedFiles = await require_listGitFiles.listGitFiles(gitOptions);
		if (gitChangedFiles) docList = docList.filter((path) => gitChangedFiles.some((gitFile) => (0, node_path.join)(process.cwd(), path) === gitFile));
	}
	appLogger(`Base locale is ${require_formatter.formatLocale(baseLocale)}`);
	appLogger(`Translating ${require_logger.colorizeNumber(locales.length)} locales: [ ${require_formatter.formatLocale(locales)} ]`);
	appLogger(`Translating ${require_logger.colorizeNumber(docList.length)} files:`);
	appLogger(docList.map((path) => ` - ${require_formatter.formatPath(path)}\n`));
	await require_parallelize.parallelize(docList.flatMap((docPath) => locales.map((locale) => async () => {
		appLogger(`Translating file: ${require_formatter.formatPath(docPath)} to ${require_formatter.formatLocale(locale)}`);
		const absoluteBaseFilePath = (0, node_path.join)(configuration.content.baseDir, docPath);
		const outputFilePath = require_getOutputFilePath.getOutputFilePath(absoluteBaseFilePath, locale, baseLocale);
		if (skipIfExists && (0, node_fs.existsSync)(outputFilePath)) {
			const relativePath = (0, node_path.relative)(configuration.content.baseDir, outputFilePath);
			appLogger(`${require_logger.colorize("⊘", require_logger.ANSIColors.YELLOW)} File ${require_formatter.formatPath(relativePath)} already exists, skipping.`);
			return;
		}
		if (!(0, node_fs.existsSync)(outputFilePath)) {
			appLogger(`File ${outputFilePath} does not exist, creating it...`);
			(0, node_fs.mkdirSync)((0, node_path.dirname)(outputFilePath), { recursive: true });
			(0, node_fs.writeFileSync)(outputFilePath, "");
		}
		const fileModificationData = require_checkFileModifiedRange.checkFileModifiedRange(outputFilePath, {
			skipIfModifiedBefore,
			skipIfModifiedAfter
		});
		if (fileModificationData.isSkipped) {
			appLogger(fileModificationData.message);
			return;
		}
		await translateFile(absoluteBaseFilePath, outputFilePath, locale, baseLocale, configuration, aiOptions, customInstructions);
	})), (task) => task(), nbSimultaneousFileProcessed ?? 3);
};

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