import { existsSync } from 'node:fs';
import a from './index5.mjs';
import { i as inquirer } from './index6.mjs';
import { r as readMcpConfig, M as MCP_SERVICE_CONFIGS, g as getMcpServices } from './claude-config.mjs';
import { DEFAULT_CODE_TOOL_TYPE, resolveCodeToolType as resolveCodeToolType$1, isCodeToolType } from './constants.mjs';
import { i18n } from './index2.mjs';
import { displayBanner } from './banner.mjs';
import { readZcfConfig, updateZcfConfig } from './ccjk-config.mjs';
import { r as runCodexUpdate } from './codex.mjs';
import { c as copyConfigFiles } from './config.mjs';
import { n as needsMigration, m as migrateSettingsForTokenRetrieval, d as displayMigrationResult, p as promptMigration } from '../shared/ccjk.BXv8aYs1.mjs';
import { u as updatePromptOnly } from '../shared/ccjk.L7yC58_i.mjs';
import { h as handleExitPromptError, a as handleGeneralError } from '../shared/ccjk.BtrioX1Z.mjs';
import { a as installMcpServices } from '../shared/ccjk.CwGZSTAK.mjs';
import { resolveAiOutputLanguage } from './prompts.mjs';
import { g as getRuntimeVersion } from '../shared/ccjk.gDEDGD_t.mjs';
import { r as resolveClaudeFamilySettingsTarget } from '../shared/ccjk.DDL-4C-k.mjs';
import { checkClaudeCodeVersionAndPrompt } from './version-checker.mjs';
import { s as selectAndInstallWorkflows } from '../shared/ccjk.BLsIiTqO.mjs';
import '../shared/ccjk.BAGoDD49.mjs';
import 'node:readline';
import 'stream';
import 'node:tty';
import 'node:process';
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:os';
import 'node:crypto';
import 'buffer';
import 'string_decoder';
import 'node:child_process';
import './json-config.mjs';
import '../shared/ccjk.RyizuzOI.mjs';
import './fs-operations.mjs';
import 'node:fs/promises';
import '../shared/ccjk.bQ7Dh1g4.mjs';
import './platform.mjs';
import './main.mjs';
import 'module';
import 'node:stream';
import 'node:url';
import '../shared/ccjk.BBtCGd_g.mjs';
import './index3.mjs';
import './index8.mjs';
import '../shared/ccjk.DeWpAShp.mjs';
import '../shared/ccjk.CxpGa6MC.mjs';
import '../shared/ccjk.BFQ7yr5S.mjs';
import '../shared/ccjk.DZ2LLOa-.mjs';
import '../shared/ccjk.C0WLUnFV.mjs';

const ccjkVersion = getRuntimeVersion();
function resolveCodeToolType(optionValue, savedValue) {
  if (optionValue !== void 0) {
    const resolved = resolveCodeToolType$1(optionValue);
    if (resolved !== DEFAULT_CODE_TOOL_TYPE || optionValue === DEFAULT_CODE_TOOL_TYPE) {
      return resolved;
    }
  }
  if (savedValue && isCodeToolType(savedValue)) {
    return savedValue;
  }
  return DEFAULT_CODE_TOOL_TYPE;
}
async function checkAndPromptNewMcpServices(codeToolType, skipPrompt) {
  try {
    const mcpConfig = readMcpConfig(codeToolType);
    const installedIds = new Set(Object.keys(mcpConfig?.mcpServers || {}));
    const newServices = MCP_SERVICE_CONFIGS.filter(
      (c) => c.defaultSelected && !installedIds.has(c.id)
    );
    if (newServices.length === 0)
      return;
    const allServices = await getMcpServices();
    const newServiceNames = newServices.map((c) => allServices.find((s) => s.id === c.id)?.name || c.id).join(", ");
    console.log(a.cyan(`
\u2728 New recommended services available: ${a.bold(newServiceNames)}`));
    if (skipPrompt) {
      await installMcpServices(newServices.map((s) => s.id), codeToolType);
      console.log(a.green("\u2713 New services installed automatically"));
      return;
    }
    const { install } = await inquirer.prompt([
      {
        type: "confirm",
        name: "install",
        message: `Install new recommended MCP services? (${newServiceNames})`,
        default: true
      }
    ]);
    if (install) {
      await installMcpServices(newServices.map((s) => s.id), codeToolType);
      console.log(a.green("\u2713 New services installed"));
    }
  } catch {
  }
}
async function update(options = {}) {
  try {
    if (!options.skipBanner) {
      displayBanner(i18n.t("cli:banner.updateSubtitle"));
    }
    const zcfConfig = readZcfConfig();
    const codeToolType = resolveCodeToolType(options.codeType, zcfConfig?.codeToolType);
    options.codeType = codeToolType;
    if (codeToolType === "codex") {
      await runCodexUpdate();
      const newPreferredLang = options.configLang || zcfConfig?.preferredLang;
      if (newPreferredLang) {
        updateZcfConfig({
          version: ccjkVersion,
          preferredLang: newPreferredLang,
          codeToolType
        });
      } else {
        updateZcfConfig({
          version: ccjkVersion,
          codeToolType
        });
      }
      return;
    }
    const { resolveTemplateLanguage } = await import('./prompts.mjs');
    const configLang = await resolveTemplateLanguage(
      options.configLang,
      // Command line option
      zcfConfig,
      options.skipPrompt,
      // Non-interactive mode flag
      codeToolType
    );
    const aiOutputLang = await resolveAiOutputLanguage(i18n.language, options.aiOutputLang, zcfConfig, options.skipPrompt);
    const runtimeTarget = resolveClaudeFamilySettingsTarget(codeToolType);
    if (existsSync(runtimeTarget.settingsFile) && needsMigration(codeToolType)) {
      if (options.skipPrompt) {
        console.log(a.yellow("\n\u26A0\uFE0F  Problematic configuration detected. Auto-fixing...\n"));
        const result = migrateSettingsForTokenRetrieval(codeToolType);
        displayMigrationResult(result);
      } else {
        const shouldMigrate = await promptMigration();
        if (shouldMigrate) {
          const result = migrateSettingsForTokenRetrieval(codeToolType);
          displayMigrationResult(result);
        }
      }
    }
    console.log(a.green(`
${i18n.t("configuration:updatingPrompts")}
`));
    console.log(a.dim("\u2714 Checking and fixing configuration format...\n"));
    copyConfigFiles(false, codeToolType);
    await updatePromptOnly(aiOutputLang, codeToolType);
    await selectAndInstallWorkflows(configLang, void 0, { codeToolType });
    await checkAndPromptNewMcpServices(codeToolType, options.skipPrompt);
    await checkClaudeCodeVersionAndPrompt(false);
    updateZcfConfig({
      version: ccjkVersion,
      templateLang: configLang,
      // 保存模板语言选择
      aiOutputLang,
      codeToolType
    });
  } catch (error) {
    if (!handleExitPromptError(error)) {
      handleGeneralError(error);
    }
  }
}

export { update };
