import type { InterpolationParams, TranslationMap } from './types';

export const resolveKey = (translations: TranslationMap, locale: string, key: string): string => {
  const value = walkPath(translations[locale], key) ?? walkPath(translations['en'], key);
  return typeof value === 'string' ? value : key;
};

const walkPath = (obj: unknown, path: string): unknown => {
  let current = obj;
  for (const segment of path.split('.')) {
    if (current == null || typeof current !== 'object') return undefined;
    current = (current as Record<string, unknown>)[segment];
  }
  return current;
};

export const interpolate = (template: string, params?: InterpolationParams): string => {
  if (!params) return template;
  return template.replace(/\{\{(\w+)\}\}/g, (_, key: string) => String(params[key] ?? `{{${key}}}`));
};
