const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
const require_utils_checkAccess = require('./utils/checkAccess.cjs');
const require__utils_asset = require('./_virtual/_utils_asset.cjs');
const require_utils_chunkInference = require('./utils/chunkInference.cjs');
const require_utils_fixChunkStartEndChars = require('./utils/fixChunkStartEndChars.cjs');
const require_utils_checkFileModifiedRange = require('./utils/checkFileModifiedRange.cjs');
const require_utils_getOutputFilePath = require('./utils/getOutputFilePath.cjs');
const require_utils_calculateChunks = require('./utils/calculateChunks.cjs');
let __intlayer_chokidar = require("@intlayer/chokidar");
let __intlayer_config = require("@intlayer/config");
let node_path = require("node:path");
let node_fs = require("node:fs");
let node_fs_promises = require("node:fs/promises");
let fast_glob = require("fast-glob");
fast_glob = require_rolldown_runtime.__toESM(fast_glob);

//#region src/translateDoc.ts
/**
* Translate a single file for a given locale
*/
const translateFile = async (baseFilePath, outputFilePath, locale, baseLocale, configuration, aiOptions, customInstructions) => {
	try {
		const appLogger = (0, __intlayer_config.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}}", `${(0, __intlayer_chokidar.formatLocale)(locale, false)}`).replaceAll("{{baseLocaleName}}", `${(0, __intlayer_chokidar.formatLocale)(baseLocale, false)}`).replace("{{applicationContext}}", aiOptions?.applicationContext ?? "-").replace("{{customInstructions}}", customInstructions ?? "-");
		const filePrefix = [(0, __intlayer_config.colon)(`${__intlayer_config.ANSIColors.GREY_DARK}[${(0, __intlayer_chokidar.formatPath)(baseFilePath)}${__intlayer_config.ANSIColors.GREY_DARK}] `, { colSize: 40 }), `→ ${__intlayer_config.ANSIColors.RESET}`].join("");
		const prefix = [(0, __intlayer_config.colon)(`${__intlayer_config.ANSIColors.GREY_DARK}[${(0, __intlayer_chokidar.formatPath)(baseFilePath)}${__intlayer_config.ANSIColors.GREY_DARK}][${(0, __intlayer_chokidar.formatLocale)(locale)}${__intlayer_config.ANSIColors.GREY_DARK}] `, { colSize: 40 }), `→ ${__intlayer_config.ANSIColors.RESET}`].join("");
		const chunks = require_utils_calculateChunks.chunkText(fileContent);
		appLogger(`${filePrefix}Base file splitted into ${(0, __intlayer_config.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 ${(0, __intlayer_chokidar.formatLocale)(locale)}:\n///chunkStart///` + (0, __intlayer_chokidar.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 ${(0, __intlayer_chokidar.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 (0, __intlayer_config.retryManager)(async () => {
				const result = await require_utils_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 ${(0, __intlayer_config.colorizeNumber)(i + 1)} of ${(0, __intlayer_config.colorizeNumber)(chunks.length)}** in ${(0, __intlayer_chokidar.formatLocale)(baseLocale, false)} to translate in ${(0, __intlayer_chokidar.formatLocale)(locale, false)}:`
					},
					{
						role: "user",
						content: fileToTranslateCurrentChunk
					}
				], aiOptions, configuration);
				appLogger([
					`${prefix}`,
					`${__intlayer_config.ANSIColors.GREY_DARK}[Chunk `,
					(0, __intlayer_config.colorizeNumber)(i + 1),
					`${__intlayer_config.ANSIColors.GREY_DARK} of `,
					(0, __intlayer_config.colorizeNumber)(chunks.length),
					`${__intlayer_config.ANSIColors.GREY_DARK}] →${__intlayer_config.ANSIColors.RESET} `,
					`${(0, __intlayer_config.colorizeNumber)(result.tokenUsed)} tokens used`
				].join(""));
				return require_utils_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(`${(0, __intlayer_config.colorize)("✔", __intlayer_config.ANSIColors.GREEN)} File ${(0, __intlayer_chokidar.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 = (0, __intlayer_config.getConfiguration)(configOptions);
	const appLogger = (0, __intlayer_config.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_utils_checkAccess.checkAIAccess(configuration, aiOptions)) return;
	if (gitOptions) {
		const gitChangedFiles = await (0, __intlayer_chokidar.listGitFiles)(gitOptions);
		if (gitChangedFiles) docList = docList.filter((path) => gitChangedFiles.some((gitFile) => (0, node_path.join)(process.cwd(), path) === gitFile));
	}
	appLogger(`Base locale is ${(0, __intlayer_chokidar.formatLocale)(baseLocale)}`);
	appLogger(`Translating ${(0, __intlayer_config.colorizeNumber)(locales.length)} locales: [ ${(0, __intlayer_chokidar.formatLocale)(locales)} ]`);
	appLogger(`Translating ${(0, __intlayer_config.colorizeNumber)(docList.length)} files:`);
	appLogger(docList.map((path) => ` - ${(0, __intlayer_chokidar.formatPath)(path)}\n`));
	await (0, __intlayer_chokidar.parallelize)(docList.flatMap((docPath) => locales.map((locale) => async () => {
		appLogger(`Translating file: ${(0, __intlayer_chokidar.formatPath)(docPath)} to ${(0, __intlayer_chokidar.formatLocale)(locale)}`);
		const absoluteBaseFilePath = (0, node_path.join)(configuration.content.baseDir, docPath);
		const outputFilePath = require_utils_getOutputFilePath.getOutputFilePath(absoluteBaseFilePath, locale, baseLocale);
		if (skipIfExists && (0, node_fs.existsSync)(outputFilePath)) {
			const relativePath = (0, node_path.relative)(configuration.content.baseDir, outputFilePath);
			appLogger(`${(0, __intlayer_config.colorize)("⊘", __intlayer_config.ANSIColors.YELLOW)} File ${(0, __intlayer_chokidar.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_utils_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;
exports.translateFile = translateFile;
//# sourceMappingURL=translateDoc.cjs.map