import { existsSync, readFileSync } from 'fs';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
const pkgRoot = join(dirname(fileURLToPath(import.meta.url)), '..');
function loadDict(locale) {
    const path = join(pkgRoot, 'locales', `${locale}.json`);
    if (!existsSync(path))
        return {};
    return JSON.parse(readFileSync(path, 'utf-8'));
}
function resolveLocale() {
    const forced = process.env.CURSORCONNECT_LANG?.trim().toLowerCase();
    if (forced === 'ru' || forced === 'en')
        return forced;
    const lang = (process.env.LANG ?? process.env.LC_ALL ?? 'en').toLowerCase();
    if (lang.startsWith('ru'))
        return 'ru';
    return 'en';
}
const en = loadDict('en');
const ru = loadDict('ru');
let locale = resolveLocale();
export function getCliLocale() {
    return locale;
}
export function setCliLocale(next) {
    locale = next;
}
function lookup(dict, key) {
    const parts = key.split('.');
    let cur = dict;
    for (const p of parts) {
        if (cur == null || typeof cur !== 'object')
            return undefined;
        cur = cur[p];
    }
    return typeof cur === 'string' ? cur : undefined;
}
/** English first; Russian from LANG/LC_ALL or CURSORCONNECT_LANG=ru */
export function t(key, params) {
    const primary = locale === 'en' ? en : ru;
    const fallback = locale === 'en' ? ru : en;
    let out = lookup(primary, key) ?? lookup(fallback, key) ?? key;
    if (params) {
        for (const [k, v] of Object.entries(params)) {
            out = out.replaceAll(`{{${k}}}`, String(v));
        }
    }
    return out;
}
