import { getContentDeclarationFileTemplate } from "../getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.mjs";
import { getFormatFromExtension } from "../utils/getFormatFromExtension.mjs";
import { transformJSFile } from "./transformJSFile.mjs";
import { detectFormatCommand } from "./detectFormatCommand.mjs";
import { extname } from "node:path";
import { readFile, writeFile } from "node:fs/promises";
import { existsSync } from "node:fs";
import { getAppLogger, logger } from "@intlayer/config";
import { execSync } from "node:child_process";

//#region ../chokidar/dist/esm/writeContentDeclaration/writeJSFile.mjs
/**
* Updates a JavaScript/TypeScript file based on the provided JSON instructions.
* It targets a specific dictionary object within the file (identified by its 'key' property)
* and updates its 'content' entries. Currently, it focuses on modifying arguments
* of 't' (translation) function calls.
*/
const writeJSFile = async (filePath, dictionary, configuration) => {
	const mergedDictionary = {
		...configuration.dictionary,
		...dictionary
	};
	const appLogger = getAppLogger(configuration);
	if (!existsSync(filePath)) {
		const format = getFormatFromExtension(extname(filePath));
		appLogger("File does not exist, creating it", { isVerbose: true });
		await writeFile(filePath, await getContentDeclarationFileTemplate(mergedDictionary.key, format, Object.fromEntries(Object.entries({
			id: mergedDictionary.id,
			locale: mergedDictionary.locale,
			filled: mergedDictionary.filled,
			fill: mergedDictionary.fill,
			description: mergedDictionary.description,
			title: mergedDictionary.title,
			tags: mergedDictionary.tags,
			version: mergedDictionary.version,
			priority: mergedDictionary.priority,
			live: mergedDictionary.live
		}).filter(([, value]) => value !== void 0))), "utf-8");
	}
	const finalCode = await transformJSFile(await readFile(filePath, "utf-8"), dictionary);
	try {
		await writeFile(filePath, finalCode, "utf-8");
		logger(`Successfully updated ${filePath}`, {
			level: "info",
			isVerbose: true
		});
	} catch (error) {
		const err = error;
		logger(`Failed to write updated file: ${filePath}`, { level: "error" });
		throw new Error(`Failed to write updated file ${filePath}: ${err.message}`);
	}
	const formatCommand = detectFormatCommand(configuration);
	if (formatCommand) try {
		execSync(formatCommand.replace("{{file}}", filePath), {
			stdio: "inherit",
			cwd: configuration.content.baseDir
		});
	} catch (error) {
		console.error(error);
	}
};

//#endregion
export { writeJSFile };
//# sourceMappingURL=writeJSFile.mjs.map