import { checkAIAccess } from "./utils/checkAccess.mjs";
import { readAsset } from "./_virtual/_utils_asset.mjs";
import { chunkInference } from "./utils/chunkInference.mjs";
import { fixChunkStartEndChars } from "./utils/fixChunkStartEndChars.mjs";
import { checkFileModifiedRange } from "./utils/checkFileModifiedRange.mjs";
import { getOutputFilePath } from "./utils/getOutputFilePath.mjs";
import { chunkText } from "./utils/calculateChunks.mjs";
import { formatLocale, formatPath, getChunk, listGitFiles, parallelize } from "@intlayer/chokidar";
import { ANSIColors, colon, colorize, colorizeNumber, getAppLogger, getConfiguration, retryManager } from "@intlayer/config";
import { dirname, join, relative } from "node:path";
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
import { readFile } from "node:fs/promises";
import fg from "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 = getAppLogger(configuration, { config: { prefix: "" } });
		const fileContent = await readFile(baseFilePath, "utf-8");
		let fileResultContent = fileContent;
		const basePrompt = readAsset("./prompts/TRANSLATE_PROMPT.md", "utf-8").replaceAll("{{localeName}}", `${formatLocale(locale, false)}`).replaceAll("{{baseLocaleName}}", `${formatLocale(baseLocale, false)}`).replace("{{applicationContext}}", aiOptions?.applicationContext ?? "-").replace("{{customInstructions}}", customInstructions ?? "-");
		const filePrefix = [colon(`${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}] `, { colSize: 40 }), `→ ${ANSIColors.RESET}`].join("");
		const prefix = [colon(`${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}][${formatLocale(locale)}${ANSIColors.GREY_DARK}] `, { colSize: 40 }), `→ ${ANSIColors.RESET}`].join("");
		const chunks = chunkText(fileContent);
		appLogger(`${filePrefix}Base file splitted into ${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 ${formatLocale(locale)}:\n///chunkStart///` + 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 ${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 retryManager(async () => {
				const result = await 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 ${colorizeNumber(i + 1)} of ${colorizeNumber(chunks.length)}** in ${formatLocale(baseLocale, false)} to translate in ${formatLocale(locale, false)}:`
					},
					{
						role: "user",
						content: fileToTranslateCurrentChunk
					}
				], aiOptions, configuration);
				appLogger([
					`${prefix}`,
					`${ANSIColors.GREY_DARK}[Chunk `,
					colorizeNumber(i + 1),
					`${ANSIColors.GREY_DARK} of `,
					colorizeNumber(chunks.length),
					`${ANSIColors.GREY_DARK}] →${ANSIColors.RESET} `,
					`${colorizeNumber(result.tokenUsed)} tokens used`
				].join(""));
				return fixChunkStartEndChars(result?.fileContent, fileToTranslateCurrentChunk);
			})();
			fileResultContent = fileResultContent.replace(fileToTranslateCurrentChunk, chunkTranslation);
		}
		mkdirSync(dirname(outputFilePath), { recursive: true });
		writeFileSync(outputFilePath, fileResultContent);
		const relativePath = relative(configuration.content.baseDir, outputFilePath);
		appLogger(`${colorize("✔", ANSIColors.GREEN)} File ${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 = getConfiguration(configOptions);
	const appLogger = 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 fg(docPattern, { ignore: excludedGlobPattern });
	if (!await checkAIAccess(configuration, aiOptions)) return;
	if (gitOptions) {
		const gitChangedFiles = await listGitFiles(gitOptions);
		if (gitChangedFiles) docList = docList.filter((path) => gitChangedFiles.some((gitFile) => join(process.cwd(), path) === gitFile));
	}
	appLogger(`Base locale is ${formatLocale(baseLocale)}`);
	appLogger(`Translating ${colorizeNumber(locales.length)} locales: [ ${formatLocale(locales)} ]`);
	appLogger(`Translating ${colorizeNumber(docList.length)} files:`);
	appLogger(docList.map((path) => ` - ${formatPath(path)}\n`));
	await parallelize(docList.flatMap((docPath) => locales.map((locale) => async () => {
		appLogger(`Translating file: ${formatPath(docPath)} to ${formatLocale(locale)}`);
		const absoluteBaseFilePath = join(configuration.content.baseDir, docPath);
		const outputFilePath = getOutputFilePath(absoluteBaseFilePath, locale, baseLocale);
		if (skipIfExists && existsSync(outputFilePath)) {
			const relativePath = relative(configuration.content.baseDir, outputFilePath);
			appLogger(`${colorize("⊘", ANSIColors.YELLOW)} File ${formatPath(relativePath)} already exists, skipping.`);
			return;
		}
		if (!existsSync(outputFilePath)) {
			appLogger(`File ${outputFilePath} does not exist, creating it...`);
			mkdirSync(dirname(outputFilePath), { recursive: true });
			writeFileSync(outputFilePath, "");
		}
		const fileModificationData = 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
export { translateDoc, translateFile };
//# sourceMappingURL=translateDoc.mjs.map