// Force strict mode and setup for ESM
"use strict";
import {
  resolveBundleDir
} from "./chunk-K4WOAR4V.js";
import {
  Storage
} from "./chunk-C4K3FEQ2.js";
import {
  init_esbuild_shims
} from "./chunk-A4BMJM77.js";
import {
  __glob,
  __name
} from "./chunk-J2S4EL5Y.js";

// packages/cli/src/utils/stdioHelpers.ts
init_esbuild_shims();
var writeStdoutLine = /* @__PURE__ */ __name((message) => {
  process.stdout.write(message.endsWith("\n") ? message : `${message}
`);
}, "writeStdoutLine");
var writeStderrLine = /* @__PURE__ */ __name((message) => {
  process.stderr.write(message.endsWith("\n") ? message : `${message}
`);
}, "writeStderrLine");
var clearScreen = /* @__PURE__ */ __name(() => {
  console.clear();
}, "clearScreen");

// packages/cli/src/i18n/index.ts
init_esbuild_shims();
import * as fs from "node:fs";
import * as path from "node:path";
import { pathToFileURL } from "node:url";

// packages/cli/src/i18n/languages.ts
init_esbuild_shims();
var SUPPORTED_LANGUAGES = [
  {
    code: "en",
    id: "en-US",
    fullName: "English",
    nativeName: "English"
  },
  {
    code: "zh-TW",
    id: "zh-TW",
    fullName: "Traditional Chinese",
    nativeName: "\u7E41\u9AD4\u4E2D\u6587",
    strictParity: true
  },
  {
    code: "zh",
    id: "zh-CN",
    fullName: "Chinese",
    nativeName: "\u4E2D\u6587",
    strictParity: true
  },
  {
    code: "ru",
    id: "ru-RU",
    fullName: "Russian",
    nativeName: "\u0420\u0443\u0441\u0441\u043A\u0438\u0439"
  },
  {
    code: "de",
    id: "de-DE",
    fullName: "German",
    nativeName: "Deutsch"
  },
  {
    code: "ja",
    id: "ja-JP",
    fullName: "Japanese",
    nativeName: "\u65E5\u672C\u8A9E"
  },
  {
    code: "pt",
    id: "pt-BR",
    fullName: "Portuguese",
    nativeName: "Portugu\xEAs"
  },
  {
    code: "fr",
    id: "fr-FR",
    fullName: "French",
    nativeName: "Fran\xE7ais"
  },
  {
    code: "ca",
    id: "ca-ES",
    fullName: "Catalan",
    nativeName: "Catal\xE0"
  }
];
function normalizeLanguageCandidate(input) {
  return input.trim().replace(/_/g, "-").toLowerCase();
}
__name(normalizeLanguageCandidate, "normalizeLanguageCandidate");
function matchesLocaleToken(candidate, token) {
  return candidate === token || candidate.startsWith(`${token}-`) || candidate.startsWith(`${token}.`) || candidate.startsWith(`${token}@`);
}
__name(matchesLocaleToken, "matchesLocaleToken");
function getMatchedLocaleTokenLength(candidate, language) {
  const code = language.code.toLowerCase();
  const id = language.id.toLowerCase();
  if (matchesLocaleToken(candidate, id)) {
    return id.length;
  }
  if (matchesLocaleToken(candidate, code)) {
    return code.length;
  }
  return void 0;
}
__name(getMatchedLocaleTokenLength, "getMatchedLocaleTokenLength");
function resolveSupportedLanguage(input) {
  const normalized = normalizeLanguageCandidate(input);
  if (!normalized) {
    return void 0;
  }
  let bestMatch;
  for (const language of SUPPORTED_LANGUAGES) {
    if (normalized === language.fullName.toLowerCase() || language.nativeName && normalized === language.nativeName.toLowerCase()) {
      return language.code;
    }
    const tokenLength = getMatchedLocaleTokenLength(normalized, language);
    if (tokenLength !== void 0 && (!bestMatch || tokenLength > bestMatch.tokenLength)) {
      bestMatch = { code: language.code, tokenLength };
    }
  }
  return bestMatch?.code;
}
__name(resolveSupportedLanguage, "resolveSupportedLanguage");
function getLanguageNameFromLocale(locale) {
  const resolved = resolveSupportedLanguage(locale);
  const lang = resolved ? SUPPORTED_LANGUAGES.find((language) => language.code === resolved) : void 0;
  return lang?.fullName || "English";
}
__name(getLanguageNameFromLocale, "getLanguageNameFromLocale");
function getLanguageSettingsOptions() {
  return [
    { value: "auto", label: "Auto (detect from system)" },
    ...SUPPORTED_LANGUAGES.map((l) => ({
      value: l.code,
      label: l.nativeName ? `${l.nativeName} (${l.fullName})` : `${l.fullName} (${l.id})`
    }))
  ];
}
__name(getLanguageSettingsOptions, "getLanguageSettingsOptions");
function getSupportedLanguageIds(separator = "|") {
  return SUPPORTED_LANGUAGES.map((l) => l.id).join(separator);
}
__name(getSupportedLanguageIds, "getSupportedLanguageIds");

// packages/cli/src/i18n/translationDict.ts
init_esbuild_shims();
function getTranslationModuleExport(module) {
  return Object.prototype.hasOwnProperty.call(module, "default") ? module["default"] : module;
}
__name(getTranslationModuleExport, "getTranslationModuleExport");
function isTranslationDict(value) {
  return value !== null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length > 0;
}
__name(isTranslationDict, "isTranslationDict");

// packages/cli/src/i18n/mustTranslateKeys.ts
init_esbuild_shims();

// import("./locales/**/*.js") in packages/cli/src/i18n/index.ts
var globImport_locales_js = __glob({
  "./locales/ca.js": () => import("./ca-7WC7ELX6.js"),
  "./locales/de.js": () => import("./de-ACHALDED.js"),
  "./locales/en.js": () => import("./en-7OGNWWME.js"),
  "./locales/fr.js": () => import("./fr-GVKZ27MF.js"),
  "./locales/ja.js": () => import("./ja-FKZ2WZ4D.js"),
  "./locales/pt.js": () => import("./pt-SY5NCFGR.js"),
  "./locales/ru.js": () => import("./ru-FWNXJG4F.js"),
  "./locales/zh-TW.js": () => import("./zh-TW-R7WRLTJS.js"),
  "./locales/zh.js": () => import("./zh-3RMSEO5M.js")
});

// packages/cli/src/i18n/index.ts
var currentLanguage = "en";
var translations = {};
var translationCache = {};
var loadingPromises = {};
var getBuiltinLocalesDir = /* @__PURE__ */ __name(() => path.join(resolveBundleDir(import.meta.url), "locales"), "getBuiltinLocalesDir");
var getUserLocalesDir = /* @__PURE__ */ __name(() => path.join(Storage.getGlobalQwenDir(), "locales"), "getUserLocalesDir");
var getLocalePath = /* @__PURE__ */ __name((lang, useUserDir = false) => {
  const baseDir = useUserDir ? getUserLocalesDir() : getBuiltinLocalesDir();
  return path.join(baseDir, `${lang}.js`);
}, "getLocalePath");
function detectSystemLanguage() {
  const envLang = process.env["QWEN_CODE_LANG"] || process.env["LANG"];
  if (envLang) {
    const resolved = resolveSupportedLanguage(envLang);
    if (resolved) {
      return resolved;
    }
  }
  try {
    const locale = Intl.DateTimeFormat().resolvedOptions().locale;
    const resolved = resolveSupportedLanguage(locale);
    if (resolved) {
      return resolved;
    }
  } catch {
  }
  return "en";
}
__name(detectSystemLanguage, "detectSystemLanguage");
async function tryImportTranslations(moduleSpecifier) {
  try {
    const module = await import(moduleSpecifier);
    const result = getTranslationModuleExport(module);
    if (isTranslationDict(result)) {
      return { translations: result };
    }
    return {
      error: new Error("Module loaded but result is empty or invalid")
    };
  } catch (error) {
    return {
      error: error instanceof Error ? error : new Error(String(error))
    };
  }
}
__name(tryImportTranslations, "tryImportTranslations");
async function tryImportBundledTranslations(lang) {
  try {
    const module = await globImport_locales_js(`./locales/${lang}.js`);
    const result = getTranslationModuleExport(module);
    if (isTranslationDict(result)) {
      return { translations: result };
    }
    return {
      error: new Error("Module loaded but result is empty or invalid")
    };
  } catch (error) {
    return {
      error: error instanceof Error ? error : new Error(String(error))
    };
  }
}
__name(tryImportBundledTranslations, "tryImportBundledTranslations");
async function loadTranslationsAsync(lang) {
  if (translationCache[lang]) {
    return translationCache[lang];
  }
  const existingPromise = loadingPromises[lang];
  if (existingPromise) {
    return existingPromise;
  }
  const loadPromise = (async () => {
    const userJsPath = getLocalePath(lang, true);
    if (fs.existsSync(getUserLocalesDir()) && fs.existsSync(userJsPath)) {
      const userResult = await tryImportTranslations(
        pathToFileURL(userJsPath).href
      );
      if (userResult.translations) {
        translationCache[lang] = userResult.translations;
        return userResult.translations;
      }
      writeStderrLine(
        `Failed to load translations from user directory for ${lang}: ${userResult.error.message}`
      );
    }
    const builtinJsPath = getLocalePath(lang, false);
    const builtinModuleSpecifiers = [];
    if (fs.existsSync(getBuiltinLocalesDir()) && fs.existsSync(builtinJsPath)) {
      builtinModuleSpecifiers.push(pathToFileURL(builtinJsPath).href);
    }
    let lastBuiltinError;
    for (const moduleSpecifier of builtinModuleSpecifiers) {
      const builtinResult = await tryImportTranslations(moduleSpecifier);
      if (builtinResult.translations) {
        translationCache[lang] = builtinResult.translations;
        return builtinResult.translations;
      }
      lastBuiltinError = builtinResult.error;
    }
    const bundledBuiltinResult = await tryImportBundledTranslations(lang);
    if (bundledBuiltinResult.translations) {
      translationCache[lang] = bundledBuiltinResult.translations;
      return bundledBuiltinResult.translations;
    }
    lastBuiltinError = bundledBuiltinResult.error;
    if (lastBuiltinError) {
      writeStderrLine(
        `Failed to load JS translations for ${lang}: ${lastBuiltinError.message}`
      );
    }
    translationCache[lang] = {};
    return {};
  })();
  loadingPromises[lang] = loadPromise;
  loadPromise.finally(() => {
    delete loadingPromises[lang];
  });
  return loadPromise;
}
__name(loadTranslationsAsync, "loadTranslationsAsync");
function interpolate(template, params) {
  if (!params) return template;
  return template.replace(
    /\{\{(\w+)\}\}/g,
    (match, key) => params[key] ?? match
  );
}
__name(interpolate, "interpolate");
function resolveLanguage(lang) {
  if (lang === "auto") {
    return detectSystemLanguage();
  }
  return resolveSupportedLanguage(lang) ?? lang;
}
__name(resolveLanguage, "resolveLanguage");
async function setLanguageAsync(lang) {
  currentLanguage = resolveLanguage(lang);
  translations = await loadTranslationsAsync(currentLanguage);
}
__name(setLanguageAsync, "setLanguageAsync");
function getCurrentLanguage() {
  return currentLanguage;
}
__name(getCurrentLanguage, "getCurrentLanguage");
function t(key, params) {
  const translation = translations[key] ?? key;
  if (Array.isArray(translation)) {
    return key;
  }
  return interpolate(translation, params);
}
__name(t, "t");
function localizeToolDisplayName(displayName) {
  const key = `toolDisplayName.${displayName}`;
  const translated = t(key);
  return translated === key ? displayName : translated;
}
__name(localizeToolDisplayName, "localizeToolDisplayName");
function ta(key) {
  const translation = translations[key];
  if (Array.isArray(translation)) {
    return translation;
  }
  return [];
}
__name(ta, "ta");
async function initializeI18n(lang) {
  await setLanguageAsync(lang ?? "auto");
}
__name(initializeI18n, "initializeI18n");
function resolveLanguageSetting(settingsLanguage) {
  return process.env["QWEN_CODE_LANG"] || settingsLanguage || "auto";
}
__name(resolveLanguageSetting, "resolveLanguageSetting");

export {
  writeStdoutLine,
  writeStderrLine,
  clearScreen,
  SUPPORTED_LANGUAGES,
  resolveSupportedLanguage,
  getLanguageNameFromLocale,
  getLanguageSettingsOptions,
  getSupportedLanguageIds,
  detectSystemLanguage,
  setLanguageAsync,
  getCurrentLanguage,
  t,
  localizeToolDisplayName,
  ta,
  initializeI18n,
  resolveLanguageSetting
};
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Qwen team
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2026 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
