import { parallelize } from "../utils/parallelize.mjs";
import { filterInvalidDictionaries, isInvalidDictionary } from "../filterInvalidDictionaries.mjs";
import { processContentDeclaration } from "../buildIntlayerDictionary/processContentDeclaration.mjs";
import { getIntlayerBundle } from "./getIntlayerBundle.mjs";
import { join, relative } from "node:path";
import { writeFile } from "node:fs/promises";
import { getProjectRequire, loadExternalFile, localCache } from "@intlayer/config";

//#region ../@intlayer/cli/dist/esm/chokidar/dist/esm/loadDictionaries/loadContentDeclaration.mjs
const formatLocalDictionaries = (dictionariesRecord, configuration) => Object.entries(dictionariesRecord).filter(([_relativePath, dict]) => isInvalidDictionary(dict, configuration)).map(([relativePath, dict]) => ({
	...dict,
	localId: `${dict.key}::local::${relativePath}`,
	location: "local",
	filePath: relativePath
}));
const loadContentDeclarations = async (contentDeclarationFilePath, configuration, onStatusUpdate) => {
	const { build, content } = configuration;
	const { set, isValid } = localCache(configuration, ["intlayer-bundle"], { ttlMs: 1e3 * 60 * 60 * 24 * 5 });
	const filePath = join(content.cacheDir, "intlayer-bundle.cjs");
	if (!await isValid()) {
		await writeFile(filePath, await getIntlayerBundle(configuration));
		await set("ok");
	}
	try {
		const dictionariesPromises = contentDeclarationFilePath.map(async (path) => {
			return {
				relativePath: relative(configuration.content.baseDir, path),
				dictionary: await loadExternalFile(path, {
					projectRequire: build.require ?? getProjectRequire(),
					buildOptions: { banner: { js: [`globalThis.INTLAYER_FILE_PATH = '${path}';`, `globalThis.INTLAYER_BASE_DIR = '${configuration.content.baseDir}';`].join("\n") } },
					aliases: { intlayer: filePath }
				})
			};
		});
		const contentDeclarations = formatLocalDictionaries((await Promise.all(dictionariesPromises)).reduce((acc, { relativePath, dictionary }) => {
			acc[relativePath] = dictionary;
			return acc;
		}, {}), configuration);
		const listFoundDictionaries = contentDeclarations.map((declaration) => ({
			dictionaryKey: declaration.key,
			type: "local",
			status: "found"
		}));
		onStatusUpdate?.(listFoundDictionaries);
		return filterInvalidDictionaries(await parallelize(contentDeclarations, async (contentDeclaration) => {
			if (!contentDeclaration) return;
			onStatusUpdate?.([{
				dictionaryKey: contentDeclaration.key,
				type: "local",
				status: "building"
			}]);
			const processedContentDeclaration = await processContentDeclaration(contentDeclaration);
			if (!processedContentDeclaration) return;
			onStatusUpdate?.([{
				dictionaryKey: processedContentDeclaration.key,
				type: "local",
				status: "built"
			}]);
			return processedContentDeclaration;
		}), configuration);
	} finally {}
};

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