import { getUnmergedDictionaries } from "../unmerged-dictionaries-entry/dist/esm/index.mjs";
import { getPerLocaleDictionary } from "../core/dist/esm/deepTransformPlugins/getLocalizedContent.mjs";
import { getFormatFromExtension } from "../utils/getFormatFromExtension.mjs";
import { writeJSFile } from "./writeJSFile.mjs";
import { getFilteredLocalesDictionary } from "../core/dist/esm/deepTransformPlugins/getFilteredLocalesContent.mjs";
import { processContentDeclarationContent } from "./processContentDeclarationContent.mjs";
import { dirname, extname, join, resolve } from "node:path";
import { mkdir, rm, writeFile } from "node:fs/promises";
import deepEqual from "deep-equal";

//#region ../@intlayer/cli/dist/esm/chokidar/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs
const formatContentDeclaration = async (dictionary, configuration, localeList) => {
	/**
	* Clean Markdown, Insertion, File, etc. node metadata
	*/
	const processedDictionary = await processContentDeclarationContent(dictionary);
	let content = processedDictionary.content;
	/**
	* Filter locales content
	*/
	if (dictionary.locale) content = getPerLocaleDictionary(processedDictionary, dictionary.locale).content;
	else if (localeList) content = getFilteredLocalesDictionary(processedDictionary, localeList).content;
	let pluginFormatResult = {
		...dictionary,
		content
	};
	/**
	* Format the dictionary with the plugins
	*/
	for await (const plugin of configuration.plugins ?? []) if (plugin.formatOutput) {
		const formattedResult = await plugin.formatOutput?.({
			dictionary: pluginFormatResult,
			configuration
		});
		if (formattedResult) pluginFormatResult = formattedResult;
	}
	if (!(pluginFormatResult.content && pluginFormatResult.key)) return pluginFormatResult;
	let result = {
		key: dictionary.key,
		id: dictionary.id,
		title: dictionary.title,
		description: dictionary.description,
		tags: dictionary.tags,
		locale: dictionary.locale,
		fill: dictionary.fill,
		filled: dictionary.filled,
		priority: dictionary.priority,
		live: dictionary.live,
		version: dictionary.version,
		content
	};
	if (getFormatFromExtension(dictionary.filePath ? extname(dictionary.filePath) : ".json") === "json" && pluginFormatResult.content && pluginFormatResult.key) result = {
		$schema: "https://intlayer.org/schema.json",
		...result
	};
	return result;
};
const defaultOptions = { newDictionariesPath: "intlayer-dictionaries" };
const writeContentDeclaration = async (dictionary, configuration, options) => {
	const { content } = configuration;
	const { baseDir } = content;
	const { newDictionariesPath, localeList } = {
		...defaultOptions,
		...options
	};
	const newDictionaryLocationPath = join(baseDir, newDictionariesPath);
	const existingDictionary = getUnmergedDictionaries(configuration)[dictionary.key]?.find((el) => el.localId === dictionary.localId);
	const formattedContentDeclaration = await formatContentDeclaration(dictionary, configuration, localeList);
	if (existingDictionary?.filePath) {
		const isSameContent = deepEqual(existingDictionary, dictionary);
		const filePath = resolve(configuration.content.baseDir, existingDictionary.filePath);
		if (isSameContent) return {
			status: "up-to-date",
			path: filePath
		};
		await writeFileWithDirectories(filePath, formattedContentDeclaration, configuration);
		return {
			status: "updated",
			path: filePath
		};
	}
	if (dictionary.filePath) {
		const filePath = resolve(configuration.content.baseDir, dictionary.filePath);
		await writeFileWithDirectories(filePath, formattedContentDeclaration, configuration);
		return {
			status: "created",
			path: filePath
		};
	}
	const contentDeclarationPath = join(newDictionaryLocationPath, `${dictionary.key}.content.json`);
	await writeFileWithDirectories(contentDeclarationPath, formattedContentDeclaration, configuration);
	return {
		status: "imported",
		path: contentDeclarationPath
	};
};
const writeFileWithDirectories = async (absoluteFilePath, dictionary, configuration) => {
	await mkdir(dirname(absoluteFilePath), { recursive: true });
	const extension = extname(absoluteFilePath);
	if (!configuration.content.fileExtensions.map((extension$1) => extname(extension$1)).includes(extension)) throw new Error(`Invalid file extension: ${extension}, file: ${absoluteFilePath}`);
	if (extension === ".json") {
		await writeFile(absoluteFilePath, `${JSON.stringify(dictionary, null, 2)}\n`);
		return;
	}
	await writeJSFile(absoluteFilePath, dictionary, configuration);
	try {
		await rm(join(configuration.content.cacheDir, "intlayer-prepared.lock"), { recursive: true });
	} catch (error) {
		if (error && typeof error === "object" && "code" in error && error.code !== "ENOENT") throw error;
	}
};

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