"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.APP_LOCALE_DISPLAY_NAMES = exports.DEFAULT_APP_LOCALE = exports.APP_LOCALES = void 0;
exports.translate = translate;
exports.translateAllLocales = translateAllLocales;
exports.getSupportedLocales = getSupportedLocales;
exports.isAppLocale = isAppLocale;
exports.getLocaleDisplayName = getLocaleDisplayName;
const node_fs_1 = require("node:fs");
const node_path_1 = __importDefault(require("node:path"));
const branding_1 = require("../core/branding");
exports.APP_LOCALES = {
    english: "en",
    japanese: "ja",
    chinese: "zh",
};
exports.DEFAULT_APP_LOCALE = exports.APP_LOCALES.english;
exports.APP_LOCALE_DISPLAY_NAMES = {
    en: "English",
    ja: "Japanese",
    zh: "Chinese",
};
const catalogCache = new Map();
function translate(locale, key, variables = {}) {
    const template = loadCatalog(locale)[key] ?? key;
    const templateVariables = {
        ...branding_1.BRANDING_TEMPLATE_VARIABLES,
        ...variables,
    };
    return template.replace(/\{\{(\w+)\}\}/g, (_match, token) => {
        const value = templateVariables[token];
        return value === undefined ? `{{${token}}}` : String(value);
    });
}
function translateAllLocales(key) {
    return [
        ...new Set(getSupportedLocales().map((locale) => translate(locale, key))),
    ];
}
function getSupportedLocales() {
    return Object.values(exports.APP_LOCALES);
}
function isAppLocale(value) {
    return getSupportedLocales().includes(value);
}
function getLocaleDisplayName(locale) {
    return exports.APP_LOCALE_DISPLAY_NAMES[locale];
}
function loadCatalog(locale) {
    const cached = catalogCache.get(locale);
    if (cached) {
        return cached;
    }
    const filePath = node_path_1.default.resolve(__dirname, "../../locales", `${locale}.json`);
    const parsed = JSON.parse((0, node_fs_1.readFileSync)(filePath, "utf8"));
    if (!isMessageCatalog(parsed)) {
        throw new Error(`Invalid locale catalog: ${filePath}`);
    }
    catalogCache.set(locale, parsed);
    return parsed;
}
function isMessageCatalog(value) {
    if (value === null || typeof value !== "object") {
        return false;
    }
    return Object.values(value).every((entry) => typeof entry === "string");
}
