/**
 * Kasy CLI i18n entrypoint.
 *
 * Messages live in lib/utils/i18n/messages-{en,pt,es}.js — one file per
 * language so merge conflicts stay isolated and reviewers can read each
 * language end-to-end. This file only ties the three together and exposes
 * the public translator API.
 */

'use strict';

const en = require('./i18n/messages-en');
const pt = require('./i18n/messages-pt');
const es = require('./i18n/messages-es');

const LANGUAGE_CHOICES = [
  { title: 'English',     value: 'en' },
  { title: 'Português',   value: 'pt' },
  { title: 'Español',     value: 'es' },
];

const MESSAGES = { en, pt, es };

function normalizeLanguage(value) {
  if (!value) return null;

  const normalized = String(value).trim().toLowerCase().replace('_', '-');
  if (!normalized) return null;

  if (normalized.startsWith('pt') || normalized === 'portugues' || normalized === 'portuguese') {
    return 'pt';
  }
  if (normalized.startsWith('es') || normalized === 'espanol' || normalized === 'spanish') {
    return 'es';
  }
  if (normalized.startsWith('en') || normalized === 'english') {
    return 'en';
  }
  return null;
}

function detectDefaultLanguage() {
  return (
    normalizeLanguage(process.env.KASY_CLI_LANG) ||
    normalizeLanguage(process.env.LC_ALL) ||
    normalizeLanguage(process.env.LANG) ||
    'en'
  );
}

function interpolate(template, params) {
  return template.replace(/\{(\w+)\}/g, (_, key) => {
    if (Object.prototype.hasOwnProperty.call(params, key)) {
      return String(params[key]);
    }
    return `{${key}}`;
  });
}

function createTranslator(language) {
  const activeLanguage = normalizeLanguage(language) || 'en';
  const activeMessages = MESSAGES[activeLanguage] || MESSAGES.en;

  return (key, params = {}) => {
    const message = activeMessages[key] || MESSAGES.en[key] || key;
    return interpolate(message, params);
  };
}

module.exports = {
  LANGUAGE_CHOICES,
  createTranslator,
  detectDefaultLanguage,
  normalizeLanguage,
};
