import { ANSIColors, colon, colorize, colorizeKey, getAppLogger } from "../config/dist/esm/logger.mjs";
import { filterInvalidDictionaries } from "../filterInvalidDictionaries.mjs";
import { loadContentDeclarations } from "./loadContentDeclaration.mjs";
import { loadRemoteDictionaries } from "./loadRemoteDictionaries.mjs";
import { DictionariesLogger } from "./log.mjs";

//#region ../@intlayer/webpack/dist/esm/chokidar/dist/esm/loadDictionaries/loadDictionaries.mjs
let loadDictionariesStatus = [];
const logger = new 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 ANSIColors.GREEN;
		case "error": return ANSIColors.RED;
		default: return ANSIColors.BLUE;
	}
};
const printSummary = (configuration) => {
	if (configuration.log.mode !== "verbose") return;
	const appLogger = 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 = colorize(`${iconFor(rec.local)} ${rec.local}`, colorFor(rec.local));
			const coloredLocal = `${ANSIColors.GREY}[` + colorize("local: ", ANSIColors.GREY) + inner + `${ANSIColors.GREY}]${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 = colorize(`${iconFor(rec.remote)} ${rec.remote}`, colorFor(rec.remote));
			labels.push(`${ANSIColors.GREY}[` + colorize("distant: ", ANSIColors.GREY) + inner + `${ANSIColors.GREY}]${ANSIColors.RESET}`);
		}
		appLogger(` - ${colon(colorizeKey(key), { colSize: keys })} ${labels.join(" ")}`);
	}
};
const loadDictionaries = async (contentDeclarationsPaths, configuration) => {
	const { plugins } = configuration;
	const loadDictionariesStartTime = Date.now();
	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 loadContentDeclarations(Array.isArray(contentDeclarationsPaths) ? contentDeclarationsPaths : [contentDeclarationsPaths], configuration, setLoadDictionariesStatus);
	const localDictionariesTime = Date.now();
	const filteredLocalDictionaries = 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 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
export { loadDictionaries };
//# sourceMappingURL=loadDictionaries.mjs.map