import 'node:fs';
import { homedir } from 'node:os';
import process__default from 'node:process';
import a from './index5.mjs';
import { i as inquirer } from './index6.mjs';
import { r as readMcpConfig, f as fixWindowsMcpConfig, w as writeMcpConfig, c as backupMcpConfig, g as getMcpServices, b as buildMcpServerConfig, m as mergeMcpServers } from './claude-config.mjs';
import { SUPPORTED_LANGS, LANG_LABELS } from './constants.mjs';
import { ensureI18nInitialized, i18n, changeLanguage } from './index2.mjs';
import { readZcfConfig, updateZcfConfig } from './ccjk-config.mjs';
import { s as syncClavueActiveProviderModelSelection } from './clavue-config.mjs';
import { g as getExistingModelConfig, a as getExistingCustomModelConfig, u as updateCustomModel, d as updateDefaultModel, e as getExistingApiConfig, p as promptApiConfigurationAction, f as configureApi } from './config.mjs';
import { m as modifyApiConfigPartially, v as validateApiKey, f as formatApiKeyDisplay } from '../shared/ccjk.L7yC58_i.mjs';
import { s as selectMcpServices } from '../shared/ccjk.DhJ1kyDR.mjs';
import { a as configureOutputStyle } from '../shared/ccjk.C0WLUnFV.mjs';
import { i as isWindows } from './platform.mjs';
import { a as addNumbersToChoices } from '../shared/ccjk.BFQ7yr5S.mjs';
import { openSettingsJson, importRecommendedPermissions, importRecommendedEnv } from './simple-config.mjs';
import { p as promptBoolean } from '../shared/ccjk.DZ2LLOa-.mjs';
import { j as join } from '../shared/ccjk.bQ7Dh1g4.mjs';
import '../shared/ccjk.BAGoDD49.mjs';
import 'node:readline';
import 'stream';
import 'node:tty';
import 'node:async_hooks';
import '../shared/ccjk.Cjgrln_h.mjs';
import 'node:util';
import 'tty';
import 'fs';
import 'child_process';
import 'node:path';
import 'node:crypto';
import 'buffer';
import 'string_decoder';
import 'node:child_process';
import '../shared/ccjk.DDL-4C-k.mjs';
import './json-config.mjs';
import '../shared/ccjk.RyizuzOI.mjs';
import './fs-operations.mjs';
import 'node:fs/promises';
import 'node:url';
import '../shared/ccjk.BBtCGd_g.mjs';
import './index3.mjs';
import './main.mjs';
import 'module';
import 'node:stream';
import '../shared/ccjk.DeWpAShp.mjs';

const DEFAULT_MODEL_CHOICES = [
  {
    nameKey: "configuration:defaultModelOption",
    fallback: "Default - Let Claude Code choose",
    value: "default"
  },
  {
    nameKey: "configuration:opusModelOption",
    fallback: "Opus - Only use opus, high token consumption, use with caution",
    value: "opus"
  },
  {
    nameKey: "configuration:sonnetModelOption",
    fallback: "Sonnet - Recommended balanced model for daily coding",
    value: "sonnet"
  },
  {
    nameKey: "configuration:sonnet1mModelOption",
    fallback: "Sonnet 1M - 1M context version",
    value: "sonnet[1m]"
  },
  {
    nameKey: "configuration:customModelOption",
    fallback: "Custom - Specify custom model names",
    value: "custom"
  }
];
const CODEX_MODEL_CHOICES = [
  {
    nameKey: "configuration:codexModelOptions.gpt5Codex",
    fallback: "GPT-5-Codex - Recommended default for serious coding work",
    value: "gpt-5-codex"
  },
  {
    nameKey: "configuration:codexModelOptions.codexMiniLatest",
    fallback: "codex-mini-latest - Faster and lighter for high-frequency tasks",
    value: "codex-mini-latest"
  },
  {
    nameKey: "configuration:codexModelOptions.gpt5",
    fallback: "GPT-5 - General-purpose fallback for mixed tasks",
    value: "gpt-5"
  },
  {
    nameKey: "configuration:codexModelOptions.custom",
    fallback: "Custom - Specify custom model names",
    value: "custom"
  }
];
function formatCodexModelLabel(model) {
  const predefined = CODEX_MODEL_CHOICES.find((choice) => choice.value === model);
  if (predefined) {
    return i18n.t(predefined.nameKey) || predefined.fallback;
  }
  return model;
}
async function handleCancellation() {
  ensureI18nInitialized();
  console.log(a.yellow(i18n.t("common:cancelled")));
}
async function handleCustomApiMode() {
  ensureI18nInitialized();
  const zcfConfig = readZcfConfig();
  const codeToolType = zcfConfig?.codeToolType || "claude-code";
  if (codeToolType === "claude-code" || codeToolType === "clavue") {
    const { configureIncrementalManagement } = await import('./claude-code-incremental-manager.mjs');
    await configureIncrementalManagement();
    return;
  }
  const existingConfig = getExistingApiConfig();
  if (existingConfig) {
    const configAction = await promptApiConfigurationAction();
    if (configAction === "keep-existing") {
      console.log(a.green(`\u2714 ${i18n.t("api:keepExistingConfig")}`));
      return;
    } else if (configAction === "modify-partial") {
      await modifyApiConfigPartially(existingConfig);
      return;
    }
  }
  const { apiChoice } = await inquirer.prompt({
    type: "list",
    name: "apiChoice",
    message: i18n.t("api:configureApi"),
    choices: addNumbersToChoices([
      {
        name: `${i18n.t("api:useAuthToken")} - ${a.gray(i18n.t("api:authTokenDesc"))}`,
        value: "auth_token",
        short: i18n.t("api:useAuthToken")
      },
      {
        name: `${i18n.t("api:useApiKey")} - ${a.gray(i18n.t("api:apiKeyDesc"))}`,
        value: "api_key",
        short: i18n.t("api:useApiKey")
      },
      { name: i18n.t("api:skipApi"), value: "skip" }
    ])
  });
  if (!apiChoice || apiChoice === "skip") {
    await handleCancellation();
    return;
  }
  const { url } = await inquirer.prompt({
    type: "input",
    name: "url",
    message: `${i18n.t("api:enterApiUrl")}${i18n.t("common:emptyToSkip")}`,
    validate: (value) => {
      if (!value) {
        return true;
      }
      try {
        void new URL(value);
        return true;
      } catch {
        return i18n.t("api:invalidUrl");
      }
    }
  });
  if (url === void 0 || !url) {
    await handleCancellation();
    return;
  }
  const keyMessage = apiChoice === "auth_token" ? `${i18n.t("api:enterAuthToken")}${i18n.t("common:emptyToSkip")}` : `${i18n.t("api:enterApiKey")}${i18n.t("common:emptyToSkip")}`;
  const { key } = await inquirer.prompt({
    type: "input",
    name: "key",
    message: keyMessage,
    validate: (value) => {
      if (!value) {
        return true;
      }
      const validation = validateApiKey(value);
      if (!validation.isValid) {
        return validation.error || i18n.t("api:invalidKeyFormat");
      }
      return true;
    }
  });
  if (key === void 0 || !key) {
    await handleCancellation();
    return;
  }
  const apiConfig = { url, key, authType: apiChoice };
  const configuredApi = configureApi(apiConfig);
  if (configuredApi) {
    console.log(a.green(`\u2714 ${i18n.t("api:apiConfigSuccess")}`));
    console.log(a.gray(`  URL: ${configuredApi.url}`));
    console.log(a.gray(`  Key: ${formatApiKeyDisplay(configuredApi.key)}`));
  }
}
async function configureMcpFeature() {
  ensureI18nInitialized();
  if (isWindows()) {
    const fixWindows = await promptBoolean({
      message: i18n.t("configuration:fixWindowsMcp") || "Fix Windows MCP configuration?",
      defaultValue: true
    });
    if (fixWindows) {
      const existingConfig = readMcpConfig() || { mcpServers: {} };
      const fixedConfig = fixWindowsMcpConfig(existingConfig);
      writeMcpConfig(fixedConfig);
      console.log(a.green(`\u2714 ${i18n.t("configuration:windowsMcpConfigFixed")}`));
    }
  }
  const selectedServices = await selectMcpServices();
  if (!selectedServices) {
    return;
  }
  if (selectedServices.length > 0) {
    const mcpBackupPath = backupMcpConfig();
    if (mcpBackupPath) {
      console.log(a.gray(`\u2714 ${i18n.t("mcp:mcpBackupSuccess")}: ${mcpBackupPath}`));
    }
    const newServers = {};
    for (const serviceId of selectedServices) {
      const service = (await getMcpServices()).find((s) => s.id === serviceId);
      if (!service)
        continue;
      let config = service.config;
      if (service.requiresApiKey) {
        const { apiKey } = await inquirer.prompt({
          type: "input",
          name: "apiKey",
          message: service.apiKeyPrompt,
          validate: async (value) => !!value || i18n.t("api:keyRequired")
        });
        if (apiKey) {
          config = buildMcpServerConfig(service.config, apiKey, service.apiKeyPlaceholder, service.apiKeyEnvVar);
        } else {
          continue;
        }
      }
      newServers[service.id] = config;
    }
    const existingConfig = readMcpConfig();
    let mergedConfig = mergeMcpServers(existingConfig, newServers);
    mergedConfig = fixWindowsMcpConfig(mergedConfig);
    writeMcpConfig(mergedConfig);
    console.log(a.green(`\u2714 ${i18n.t("mcp:mcpConfigSuccess")}`));
  }
}
async function configureDefaultModelFeature(codeTool) {
  ensureI18nInitialized();
  const codeToolType = codeTool || readZcfConfig()?.codeToolType || "claude-code";
  const existingModel = getExistingModelConfig(codeToolType);
  if (existingModel) {
    console.log(`
${a.green(`\u2139 ${i18n.t("configuration:existingModelConfig") || "Existing model configuration"}`)}`);
    const modelDisplay = existingModel === "default" ? i18n.t("configuration:defaultModelOption") || "Default (Let Claude Code choose)" : existingModel.charAt(0).toUpperCase() + existingModel.slice(1);
    console.log(a.gray(`  ${i18n.t("configuration:currentModel") || "Current model"}: ${modelDisplay}
`));
    const modify = await promptBoolean({
      message: i18n.t("configuration:modifyModel") || "Modify model configuration?",
      defaultValue: false
    });
    if (!modify) {
      console.log(a.green(`\u2714 ${i18n.t("configuration:keepModel") || "Keeping existing model configuration"}`));
      return;
    }
  }
  const { model } = await inquirer.prompt({
    type: "list",
    name: "model",
    message: i18n.t("configuration:selectDefaultModel") || "Select default model",
    choices: DEFAULT_MODEL_CHOICES.map((choice) => ({
      name: i18n.t(choice.nameKey) || choice.fallback,
      value: choice.value
    })),
    default: existingModel ? DEFAULT_MODEL_CHOICES.findIndex((choice) => choice.value === existingModel) : 0
  });
  if (!model) {
    await handleCancellation();
    return;
  }
  if (model === "custom") {
    const existingCustomConfig = getExistingCustomModelConfig(codeToolType);
    const { primaryModel, haikuModel, sonnetModel, opusModel } = await promptCustomModels(
      existingCustomConfig?.primaryModel,
      existingCustomConfig?.haikuModel,
      existingCustomConfig?.sonnetModel,
      existingCustomConfig?.opusModel
    );
    if (!primaryModel.trim() && !haikuModel.trim() && !sonnetModel.trim() && !opusModel.trim()) {
      console.log(a.yellow(`\u26A0 ${i18n.t("configuration:customModelSkipped") || "Custom model configuration skipped"}`));
      return;
    }
    updateCustomModel(primaryModel, haikuModel, sonnetModel, opusModel, codeToolType);
    if (codeToolType === "clavue") {
      syncClavueActiveProviderModelSelection({
        primaryModel,
        haikuModel,
        sonnetModel,
        opusModel
      });
    }
    console.log(a.green(`\u2714 ${i18n.t("configuration:customModelConfigured") || "Custom model configuration completed"}`));
    return;
  }
  updateDefaultModel(model, codeToolType);
  if (codeToolType === "clavue") {
    syncClavueActiveProviderModelSelection(
      model === "default" ? { reset: true } : { selectedModel: model }
    );
  }
  console.log(a.green(`\u2714 ${i18n.t("configuration:modelConfigured") || "Default model configured"}`));
}
async function promptCustomModels(defaultPrimaryModel, defaultHaikuModel, defaultSonnetModel, defaultOpusModel) {
  const { primaryModel } = await inquirer.prompt({
    type: "input",
    name: "primaryModel",
    message: `${i18n.t("configuration:enterPrimaryModel")}${i18n.t("common:emptyToSkip")}`,
    default: defaultPrimaryModel || ""
  });
  const { haikuModel } = await inquirer.prompt({
    type: "input",
    name: "haikuModel",
    message: `${i18n.t("configuration:enterHaikuModel")}${i18n.t("common:emptyToSkip")}`,
    default: defaultHaikuModel || ""
  });
  const { sonnetModel } = await inquirer.prompt({
    type: "input",
    name: "sonnetModel",
    message: `${i18n.t("configuration:enterSonnetModel")}${i18n.t("common:emptyToSkip")}`,
    default: defaultSonnetModel || ""
  });
  const { opusModel } = await inquirer.prompt({
    type: "input",
    name: "opusModel",
    message: `${i18n.t("configuration:enterOpusModel")}${i18n.t("common:emptyToSkip")}`,
    default: defaultOpusModel || ""
  });
  return { primaryModel, haikuModel, sonnetModel, opusModel };
}
async function changeScriptLanguageFeature(currentLang) {
  ensureI18nInitialized();
  const { lang } = await inquirer.prompt({
    type: "list",
    name: "lang",
    message: i18n.t("language:selectScriptLang"),
    choices: addNumbersToChoices(
      SUPPORTED_LANGS.map((l) => ({
        name: LANG_LABELS[l],
        value: l
      }))
    ),
    default: SUPPORTED_LANGS.indexOf(currentLang)
  });
  if (!lang) {
    return currentLang;
  }
  updateZcfConfig({ preferredLang: lang });
  await changeLanguage(lang);
  console.log(a.green(`\u2714 ${i18n.t("language:languageChanged") || "Language changed"}`));
  return lang;
}
async function configureCodexDefaultModelFeature() {
  ensureI18nInitialized();
  const { readCodexConfig } = await import('./codex.mjs').then(function (n) { return n.t; });
  const existingConfig = readCodexConfig();
  const currentModel = existingConfig?.model;
  if (currentModel) {
    console.log(`
${a.green(`\u2139 ${i18n.t("configuration:existingModelConfig") || "Existing model configuration"}`)}`);
    const modelDisplay = formatCodexModelLabel(currentModel);
    console.log(a.gray(`  ${i18n.t("configuration:currentModel") || "Current model"}: ${modelDisplay}
`));
    const modify = await promptBoolean({
      message: i18n.t("configuration:modifyModel") || "Modify model configuration?",
      defaultValue: false
    });
    if (!modify) {
      console.log(a.green(`\u2714 ${i18n.t("configuration:keepModel") || "Keeping existing model configuration"}`));
      return;
    }
  }
  const supportedModels = CODEX_MODEL_CHOICES.map((choice) => choice.value);
  const defaultModel = currentModel && supportedModels.includes(currentModel) ? currentModel : currentModel ? "custom" : "gpt-5-codex";
  const { model } = await inquirer.prompt({
    type: "list",
    name: "model",
    message: i18n.t("configuration:selectDefaultModel") || "Select default model",
    choices: addNumbersToChoices(CODEX_MODEL_CHOICES.map((choice) => ({
      name: i18n.t(choice.nameKey) || choice.fallback,
      value: choice.value
    }))),
    default: defaultModel
  });
  if (!model) {
    await handleCancellation();
    return;
  }
  if (model === "custom") {
    const { customModel } = await inquirer.prompt({
      type: "input",
      name: "customModel",
      message: `${i18n.t("configuration:enterCustomModel")}${i18n.t("common:emptyToSkip")}`,
      default: ""
    });
    if (!customModel.trim()) {
      console.log(a.yellow(`\u26A0 ${i18n.t("configuration:customModelSkipped") || "Custom model configuration skipped"}`));
      return;
    }
    await updateCodexModelProvider(customModel.trim());
    console.log(a.green(`\u2714 ${i18n.t("configuration:customModelConfigured") || "Custom model configuration completed"}`));
    return;
  }
  await updateCodexModelProvider(model);
  console.log(a.green(`\u2714 ${i18n.t("configuration:modelConfigured") || "Default model configured"}`));
}
async function configureCodexAiMemoryFeature() {
  ensureI18nInitialized();
  const { option } = await inquirer.prompt({
    type: "list",
    name: "option",
    message: i18n.t("configuration:selectMemoryOption") || "Select configuration option",
    choices: addNumbersToChoices([
      {
        name: i18n.t("configuration:configureAiLanguage") || "Configure AI output language",
        value: "language"
      },
      {
        name: i18n.t("configuration:configureSystemPromptStyle") || "Configure global AI system prompt style",
        value: "systemPrompt"
      }
    ])
  });
  if (!option) {
    return;
  }
  if (option === "language") {
    const zcfConfig = readZcfConfig();
    const existingLang = zcfConfig?.aiOutputLang;
    if (existingLang) {
      console.log(
        `
${a.green(`\u2139 ${i18n.t("configuration:existingLanguageConfig") || "Existing AI output language configuration"}`)}`
      );
      console.log(a.gray(`  ${i18n.t("configuration:currentLanguage") || "Current language"}: ${existingLang}
`));
      const modify = await promptBoolean({
        message: i18n.t("configuration:modifyLanguage") || "Modify AI output language?",
        defaultValue: false
      });
      if (!modify) {
        console.log(a.green(`\u2714 ${i18n.t("configuration:keepLanguage") || "Keeping existing language configuration"}`));
        await ensureLanguageDirectiveInAgents(existingLang);
        return;
      }
    }
    const { selectAiOutputLanguage } = await import('./prompts.mjs');
    const aiOutputLang = await selectAiOutputLanguage();
    await updateCodexLanguageDirective(aiOutputLang);
    updateZcfConfig({ aiOutputLang });
    console.log(a.green(`\u2714 ${i18n.t("configuration:aiLanguageConfigured") || "AI output language configured"}`));
  } else if (option === "systemPrompt") {
    const zcfConfig = readZcfConfig();
    const currentLang = zcfConfig?.aiOutputLang || "English";
    const { runCodexSystemPromptSelection } = await import('./codex.mjs').then(function (n) { return n.t; });
    await runCodexSystemPromptSelection();
    await ensureLanguageDirectiveInAgents(currentLang);
    console.log(a.green(`\u2714 ${i18n.t("configuration:systemPromptConfigured")}`));
  }
}
async function updateCodexModelProvider(modelProvider) {
  const { readCodexConfig, writeCodexConfig, backupCodexConfig, getBackupMessage } = await import('./codex.mjs').then(function (n) { return n.t; });
  const backupPath = backupCodexConfig();
  if (backupPath) {
    console.log(a.gray(getBackupMessage(backupPath)));
  }
  const existingConfig = readCodexConfig();
  const updatedConfig = {
    ...existingConfig,
    model: modelProvider,
    // Set the model field
    modelProvider: existingConfig?.modelProvider || null,
    // Preserve existing API provider
    providers: existingConfig?.providers || [],
    mcpServices: existingConfig?.mcpServices || [],
    managed: true,
    features: existingConfig?.features,
    otherConfig: existingConfig?.otherConfig || [],
    modelProviderCommented: existingConfig?.modelProviderCommented
  };
  writeCodexConfig(updatedConfig);
}
const LANG_DIRECTIVE_RE = /\*\*Most Important:\s*Always respond in [^*]+\*\*/i;
const LANG_DIRECTIVE_RE_G = /\*\*Most Important:\s*Always respond in [^*]+\*\*\s*/g;
const codexLanguageLabels = {
  "Chinese": "Chinese-simplified",
  "English": "English",
  "zh-CN": "Chinese-simplified",
  "en": "English"
};
async function setCodexLanguageDirective(aiOutputLang, mode) {
  const { readFile, writeFileAtomic, exists } = await import('./fs-operations.mjs');
  const { backupCodexAgents, getBackupMessage } = await import('./codex.mjs').then(function (n) { return n.t; });
  const CODEX_AGENTS_FILE = join(homedir(), ".codex", "AGENTS.md");
  if (!exists(CODEX_AGENTS_FILE)) {
    console.log(a.yellow(i18n.t("codex:agentsFileNotFound")));
    return;
  }
  let content = readFile(CODEX_AGENTS_FILE);
  const langLabel = codexLanguageLabels[aiOutputLang] || aiOutputLang;
  if (mode === "ensure" && LANG_DIRECTIVE_RE.test(content))
    return;
  const backupPath = backupCodexAgents();
  if (backupPath)
    console.log(a.gray(getBackupMessage(backupPath)));
  content = content.replace(LANG_DIRECTIVE_RE_G, "");
  if (!content.endsWith("\n"))
    content += "\n";
  content += `
**Most Important:Always respond in ${langLabel}**
`;
  writeFileAtomic(CODEX_AGENTS_FILE, content);
  if (mode === "ensure")
    console.log(a.gray(`  ${i18n.t("configuration:addedLanguageDirective")}: ${langLabel}`));
}
async function ensureLanguageDirectiveInAgents(aiOutputLang) {
  return setCodexLanguageDirective(aiOutputLang, "ensure");
}
async function updateCodexLanguageDirective(aiOutputLang) {
  return setCodexLanguageDirective(aiOutputLang, "update");
}
async function configureMergedPermissionsFeature() {
  ensureI18nInitialized();
  const isZh = i18n.language === "zh-CN";
  const { choice } = await inquirer.prompt({
    type: "list",
    name: "choice",
    message: isZh ? "\u6743\u9650 & \u73AF\u5883\u914D\u7F6E \u2014 \u9009\u62E9\u64CD\u4F5C:" : "Permissions & Env Setup \u2014 Select action:",
    choices: addNumbersToChoices([
      {
        name: isZh ? `\u5BFC\u5165\u63A8\u8350\u73AF\u5883\u53D8\u91CF  ${a.gray("- \u5199\u5165\u9690\u79C1\u4FDD\u62A4 env \u5230 settings.json")}` : `Import recommended env vars  ${a.gray("- Write privacy env to settings.json")}`,
        value: "env"
      },
      {
        name: isZh ? `\u5BFC\u5165\u63A8\u8350\u6743\u9650\u914D\u7F6E  ${a.gray("- \u8FFD\u52A0\u63A8\u8350 allow \u89C4\u5219\u5230 settings.json")}` : `Import recommended permissions  ${a.gray("- Append recommended allow rules")}`,
        value: "permissions"
      },
      {
        name: isZh ? `\u4E00\u952E\u6743\u9650\u9884\u8BBE  ${a.gray("- \u6700\u5927(max) / \u5F00\u53D1\u8005(dev) / \u5B89\u5168(safe) \u9884\u8BBE")}` : `Zero-config permission preset  ${a.gray("- max / dev / safe preset")}`,
        value: "preset"
      },
      {
        name: isZh ? `\u6253\u5F00 settings.json  ${a.gray("- \u5728\u7F16\u8F91\u5668\u4E2D\u67E5\u770B\u5F53\u524D\u914D\u7F6E")}` : `Open settings.json  ${a.gray("- View current config in editor")}`,
        value: "open"
      }
    ])
  });
  if (!choice) {
    await handleCancellation();
    return;
  }
  try {
    switch (choice) {
      case "env":
        await importRecommendedEnv();
        console.log(a.green(`\u2705 ${i18n.t("configuration:envImportSuccess")}`));
        break;
      case "permissions":
        await importRecommendedPermissions();
        console.log(a.green(`\u2705 ${i18n.t("configuration:permissionsImportSuccess") || "Permissions imported"}`));
        break;
      case "preset": {
        const { zeroConfig } = await import('./zero-config.mjs');
        await zeroConfig();
        break;
      }
      case "open":
        console.log(a.green(i18n.t("configuration:openingSettingsJson") || "Opening settings.json..."));
        await openSettingsJson();
        break;
    }
  } catch (error) {
    console.error(a.red(`${i18n.t("common:error")}: ${error.message}`));
  }
}
async function configureMemoryFeature() {
  ensureI18nInitialized();
  const isZh = i18n.language === "zh-CN";
  const inquirer2 = (await import('./index6.mjs').then(function (n) { return n.c; })).default;
  const ansis2 = (await import('./index5.mjs')).default;
  const { execSync } = await import('node:child_process');
  const fs = await import('node:fs/promises');
  const { getCcjkMemoryPath, getClaudeMemoryPath } = await import('./memory-paths.mjs');
  const { inspectMemoryFiles, syncMemoryFiles } = await import('./memory-sync.mjs');
  const { memoryCheck } = await import('./memory-check.mjs');
  console.log(ansis2.cyan(`
${i18n.t("memory:title")}`));
  const projectPath = process__default.cwd();
  const claudeMemoryPath = getClaudeMemoryPath(projectPath);
  const ccjkMemoryPath = getCcjkMemoryPath(projectPath);
  let claudeMemoryExists = false;
  let ccjkMemoryExists = false;
  try {
    await fs.access(claudeMemoryPath);
    claudeMemoryExists = true;
  } catch {
  }
  try {
    await fs.access(ccjkMemoryPath);
    ccjkMemoryExists = true;
  } catch {
  }
  console.log(`
${ansis2.bold(i18n.t("memory:currentStatus"))}`);
  console.log(ansis2.gray("\u2500".repeat(50)));
  console.log(`${ansis2.yellow(i18n.t("memory:claudeMemory"))}: ${claudeMemoryExists ? ansis2.green("\u2713") : ansis2.red("\u2717")}`);
  console.log(`${ansis2.yellow(i18n.t("memory:ccjkMemory"))}: ${ccjkMemoryExists ? ansis2.green("\u2713") : ansis2.red("\u2717")}`);
  console.log(ansis2.gray("\u2500".repeat(50)));
  const { action } = await inquirer2.prompt([
    {
      type: "list",
      name: "action",
      message: i18n.t("memory:selectAction"),
      choices: [
        { name: "Status", value: "status" },
        { name: "Doctor", value: "doctor" },
        { name: i18n.t("memory:viewMemory"), value: "view" },
        { name: i18n.t("memory:editMemory"), value: "edit" },
        { name: i18n.t("memory:syncNow"), value: "sync" },
        { name: i18n.t("memory:configureRules"), value: "rules" },
        { name: isZh ? "\u{1F310} \u914D\u7F6E AI \u8F93\u51FA\u8BED\u8A00" : "\u{1F310} Configure AI output language", value: "language" },
        { name: isZh ? "\u{1F3A8} \u914D\u7F6E\u8F93\u51FA\u98CE\u683C" : "\u{1F3A8} Configure output style", value: "outputStyle" },
        { name: i18n.t("memory:back"), value: "back" }
      ]
    }
  ]);
  switch (action) {
    case "status": {
      const inspection = inspectMemoryFiles({ projectPath });
      console.log(ansis2.bold("\nMemory Status"));
      console.log(ansis2.gray("\u2500".repeat(50)));
      console.log(`State: ${inspection.syncState}`);
      console.log(`Source: ${inspection.source}`);
      console.log(`Claude: ${inspection.paths.claude}`);
      console.log(`CCJK:   ${inspection.paths.ccjk}`);
      console.log(`Entries: ${inspection.entryCount}`);
      console.log(ansis2.gray("\u2500".repeat(50)));
      break;
    }
    case "doctor": {
      const health = await memoryCheck.check();
      console.log(ansis2.bold("\nMemory Doctor"));
      console.log(ansis2.gray("\u2500".repeat(50)));
      console.log(`${health.message} (${health.score}/100)`);
      for (const detail of health.details || []) {
        console.log(detail);
      }
      if (health.fix) {
        console.log(ansis2.yellow(`Fix: ${health.fix}`));
      }
      console.log(ansis2.gray("\u2500".repeat(50)));
      break;
    }
    case "view": {
      const memoryPath = getClaudeMemoryPath(projectPath);
      try {
        const content = await fs.readFile(memoryPath, "utf-8");
        console.log(`
${ansis2.bold(i18n.t("memory:memoryContent"))}`);
        console.log(ansis2.gray("\u2500".repeat(50)));
        console.log(content);
        console.log(ansis2.gray("\u2500".repeat(50)));
      } catch (_error) {
        console.log(ansis2.red(i18n.t("memory:readError")));
      }
      break;
    }
    case "edit": {
      const memoryPath = getClaudeMemoryPath(projectPath);
      const editor = process__default.env.EDITOR || "nano";
      try {
        execSync(`${editor} "${memoryPath}"`, { stdio: "inherit" });
        console.log(ansis2.green(i18n.t("memory:editComplete")));
      } catch (_error) {
        console.log(ansis2.red(i18n.t("memory:editError")));
      }
      break;
    }
    case "sync": {
      console.log(ansis2.cyan(i18n.t("memory:syncing")));
      try {
        syncMemoryFiles({ projectPath });
        console.log(ansis2.green(i18n.t("memory:syncComplete")));
      } catch (_error) {
        console.log(ansis2.red(i18n.t("memory:syncError")));
      }
      break;
    }
    case "rules": {
      console.log(ansis2.yellow(i18n.t("memory:rulesInfo")));
      console.log(i18n.t("memory:rulesDescription"));
      break;
    }
    case "language": {
      await changeScriptLanguageFeature(i18n.language);
      break;
    }
    case "outputStyle": {
      await configureOutputStyle();
      break;
    }
  }
}

export { CODEX_MODEL_CHOICES, DEFAULT_MODEL_CHOICES, changeScriptLanguageFeature, configureCodexAiMemoryFeature, configureCodexDefaultModelFeature, configureDefaultModelFeature, configureMcpFeature, configureMemoryFeature, configureMergedPermissionsFeature, formatCodexModelLabel, handleCustomApiMode, promptCustomModels };
