import { createRequire } from 'module';
import { fileURLToPath } from 'url';
import path from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const require = createRequire(import.meta.url);
const cache = {};

function load(lang) {
  if (cache[lang]) return cache[lang];
  try {
    cache[lang] = require(path.resolve(__dirname, '../i18n', `${lang}.json`));
    return cache[lang];
  } catch {
    if (lang !== 'en') return load('en');
    cache[lang] = {};
    return cache[lang];
  }
}

/**
 * Translate a dot-separated key for the given language.
 * Interpolates {placeholder} tokens from params.
 * Unresolved tokens are left as-is so callers can do HTML substitution afterwards.
 *
 * @param {string} lang    Language code, e.g. 'en', 'de'
 * @param {string} keyPath Dot-separated key, e.g. 'email.verify.subject'
 * @param {Record<string,string>} [params]  Values to interpolate
 * @returns {string}
 */
export function t(lang, keyPath, params = {}) {
  const keys = keyPath.split('.');

  function resolve(dict) {
    let val = dict;
    for (const k of keys) {
      val = val?.[k];
    }
    return typeof val === 'string' ? val : undefined;
  }

  let value = resolve(load(lang));
  // Fallback to English
  if (value === undefined) value = resolve(load('en'));
  if (value === undefined) return keyPath;

  return value.replace(/\{(\w+)\}/g, (match, k) =>
    params[k] !== undefined ? String(params[k]) : match
  );
}
