import * as generatedMessages from '$lib/paraglide/messages';

const normalizedMessageKeyCache = new Map<string, string>();
const generatedMessagesAny: Record<string, unknown> = generatedMessages;

export const m = new Proxy({} as typeof generatedMessages, {
	get(_target, property: string | symbol) {
		if (typeof property !== 'string') {
			return undefined;
		}

		const directValue = generatedMessagesAny[property];
		if (directValue !== undefined) {
			return directValue;
		}

		const cachedKey = normalizedMessageKeyCache.get(property);
		if (cachedKey && generatedMessagesAny[cachedKey] !== undefined) {
			return generatedMessagesAny[cachedKey];
		}

		const dottedProperty = property.replace(/_/g, '.');
		if (generatedMessagesAny[dottedProperty] !== undefined) {
			normalizedMessageKeyCache.set(property, dottedProperty);
			return generatedMessagesAny[dottedProperty];
		}

		const normalizedProperty = property.replace(/\./g, '_');
		const matchingKey = Object.keys(generatedMessagesAny).find(
			(key) => key.replace(/\./g, '_') === normalizedProperty
		);
		if (matchingKey) {
			normalizedMessageKeyCache.set(property, matchingKey);
			return generatedMessagesAny[matchingKey];
		}

		return generatedMessagesAny[property];
	}
}) as typeof generatedMessages;
