const require_logger = require('../config/dist/esm/logger.cjs');
const require_filterInvalidDictionaries = require('../filterInvalidDictionaries.cjs');
const require_loadContentDeclaration = require('./loadContentDeclaration.cjs');
const require_loadRemoteDictionaries = require('./loadRemoteDictionaries.cjs');
const require_log = require('./log.cjs');

//#region ../@intlayer/cli/dist/esm/chokidar/dist/esm/loadDictionaries/loadDictionaries.mjs
let loadDictionariesStatus = [];
const logger = new require_log.DictionariesLogger();
const setLoadDictionariesStatus = (statuses) => {
	const updated = [...loadDictionariesStatus];
	for (const incoming of statuses) {
		const index = updated.findIndex((s) => s.dictionaryKey === incoming.dictionaryKey && s.type === incoming.type);
		if (index >= 0) updated[index] = incoming;
		else updated.push(incoming);
	}
	loadDictionariesStatus = updated;
	logger.update(statuses);
	return updated;
};
const iconFor = (status) => {
	switch (status) {
		case "built":
		case "imported":
		case "fetched": return "✔";
		case "error": return "✖";
		default: return "⏲";
	}
};
const colorFor = (status) => {
	switch (status) {
		case "built":
		case "imported":
		case "fetched": return require_logger.ANSIColors.GREEN;
		case "error": return require_logger.ANSIColors.RED;
		default: return require_logger.ANSIColors.BLUE;
	}
};
const printSummary = (configuration) => {
	if (configuration.log.mode !== "verbose") return;
	const appLogger = require_logger.getAppLogger(configuration);
	const byKey = /* @__PURE__ */ new Map();
	for (const s of loadDictionariesStatus) {
		const rec = byKey.get(s.dictionaryKey) ?? {};
		if (s.type === "local") rec.local = s.status;
		if (s.type === "remote") rec.remote = s.status;
		byKey.set(s.dictionaryKey, rec);
	}
	const keys = Array.from(byKey.keys()).sort((a, b) => a.localeCompare(b));
	let maxLocalLabelLen = 0;
	for (const key of keys) {
		const rec = byKey.get(key);
		if (rec.local) {
			const visibleLocal = `[local: ${iconFor(rec.local)} ${rec.local}]`;
			if (visibleLocal.length > maxLocalLabelLen) maxLocalLabelLen = visibleLocal.length;
		}
	}
	for (const key of keys) {
		const rec = byKey.get(key);
		const labels = [];
		if (rec.local) {
			const inner = require_logger.colorize(`${iconFor(rec.local)} ${rec.local}`, colorFor(rec.local));
			const coloredLocal = `${require_logger.ANSIColors.GREY}[` + require_logger.colorize("local: ", require_logger.ANSIColors.GREY) + inner + `${require_logger.ANSIColors.GREY}]${require_logger.ANSIColors.RESET}`;
			const visibleLocal = `[local: ${iconFor(rec.local)} ${rec.local}]`;
			const pad = Math.max(0, maxLocalLabelLen - visibleLocal.length);
			labels.push(coloredLocal + " ".repeat(pad));
		} else labels.push(" ".repeat(maxLocalLabelLen));
		if (rec.remote) {
			const inner = require_logger.colorize(`${iconFor(rec.remote)} ${rec.remote}`, colorFor(rec.remote));
			labels.push(`${require_logger.ANSIColors.GREY}[` + require_logger.colorize("distant: ", require_logger.ANSIColors.GREY) + inner + `${require_logger.ANSIColors.GREY}]${require_logger.ANSIColors.RESET}`);
		}
		appLogger(` - ${require_logger.colon(require_logger.colorizeKey(key), { colSize: keys })} ${labels.join(" ")}`);
	}
};
const loadDictionaries = async (contentDeclarationsPaths, configuration) => {
	const { plugins } = configuration;
	const loadDictionariesStartTime = Date.now();
	require_logger.getAppLogger(configuration)("Dictionaries:", { isVerbose: true });
	const pluginsWithLoadDictionaries = (plugins ?? []).filter((plugin) => plugin.loadDictionaries);
	logger.setPluginTotal(pluginsWithLoadDictionaries.length);
	const completedPluginIndices = /* @__PURE__ */ new Set();
	const updatePluginProgress = () => {
		logger.setPluginDone(completedPluginIndices.size);
	};
	const loadPluginDictionariesPromise = pluginsWithLoadDictionaries.map(async (plugin, index) => {
		try {
			const res = await plugin.loadDictionaries?.({ configuration });
			completedPluginIndices.add(index);
			updatePluginProgress();
			return res ?? [];
		} catch (error) {
			logger.setPluginError(error);
			completedPluginIndices.add(index);
			updatePluginProgress();
			return [];
		}
	});
	const pluginDictionaries = (await Promise.all(loadPluginDictionariesPromise)).flat();
	const localDictionaries = await require_loadContentDeclaration.loadContentDeclarations(Array.isArray(contentDeclarationsPaths) ? contentDeclarationsPaths : [contentDeclarationsPaths], configuration, setLoadDictionariesStatus);
	const localDictionariesTime = Date.now();
	const filteredLocalDictionaries = require_filterInvalidDictionaries.filterInvalidDictionaries(localDictionaries, configuration);
	setLoadDictionariesStatus(filteredLocalDictionaries.map((dict) => ({
		dictionaryKey: dict.key,
		type: "local",
		status: "built"
	})));
	const hasRemoteDictionaries = Boolean(configuration.editor.clientId && configuration.editor.clientSecret);
	if (hasRemoteDictionaries) logger.setExpectRemote(true);
	let remoteDictionaries = [];
	if (hasRemoteDictionaries) remoteDictionaries = await require_loadRemoteDictionaries.loadRemoteDictionaries(configuration, setLoadDictionariesStatus, {
		onStartRemoteCheck: () => logger.startRemoteCheck(),
		onStopRemoteCheck: () => logger.stopRemoteCheck(),
		onError: (e) => logger.setRemoteError(e)
	});
	const remoteDictionariesTime = Date.now();
	const pluginDictionariesTime = Date.now();
	logger.finish();
	printSummary(configuration);
	return {
		localDictionaries: filteredLocalDictionaries,
		remoteDictionaries,
		pluginDictionaries,
		time: {
			localDictionaries: localDictionariesTime - loadDictionariesStartTime,
			remoteDictionaries: remoteDictionariesTime - localDictionariesTime,
			pluginDictionaries: pluginDictionariesTime - remoteDictionariesTime
		}
	};
};

//#endregion
exports.loadDictionaries = loadDictionaries;
//# sourceMappingURL=loadDictionaries.cjs.map