import process__default from 'node:process';
import a from './index5.mjs';
import { i as inquirer } from './index6.mjs';
import { resolveCodeToolType, isCodeToolType, DEFAULT_CODE_TOOL_TYPE } from './constants.mjs';
import { ensureI18nInitialized, i18n } from './index2.mjs';
import { readZcfConfig } from './ccjk-config.mjs';
import { C as ClaudeCodeConfigManager, a as setMyclaudeActiveProviderProfile, b as syncMyclaudeProviderProfilesFromClaudeConfig } from './clavue-config.mjs';
import { s as switchToOfficialLogin, c as switchToProvider, l as listCodexProviders, a as readCodexConfig } from './codex.mjs';
import { a as handleGeneralError } from '../shared/ccjk.BtrioX1Z.mjs';
import { a as addNumbersToChoices } from '../shared/ccjk.BFQ7yr5S.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:os';
import 'node:crypto';
import 'buffer';
import 'string_decoder';
import '../shared/ccjk.bQ7Dh1g4.mjs';
import 'node:fs';
import 'node:url';
import '../shared/ccjk.BBtCGd_g.mjs';
import './index3.mjs';
import './fs-operations.mjs';
import 'node:fs/promises';
import './json-config.mjs';
import '../shared/ccjk.RyizuzOI.mjs';
import '../shared/ccjk.DDL-4C-k.mjs';
import './config.mjs';
import './claude-config.mjs';
import 'node:child_process';
import './platform.mjs';
import './main.mjs';
import 'module';
import 'node:stream';
import './index8.mjs';
import '../shared/ccjk.DeWpAShp.mjs';
import '../shared/ccjk.CxpGa6MC.mjs';
import './prompts.mjs';
import '../shared/ccjk.gDEDGD_t.mjs';
import '../shared/ccjk.DZ2LLOa-.mjs';

async function configSwitchCommand(options) {
  try {
    ensureI18nInitialized();
    if (options.list) {
      await handleList(options.codeType);
      return;
    }
    if (options.target) {
      const resolvedCodeType = resolveCodeType(options.codeType);
      await handleDirectSwitch(resolvedCodeType, options.target);
      return;
    }
    await handleInteractiveSwitch(options.codeType);
  } catch (error) {
    if (process__default.env.NODE_ENV === "test" || process__default.env.VITEST) {
      throw error;
    }
    handleGeneralError(error);
  }
}
function resolveCodeType(codeType) {
  if (codeType !== void 0) {
    const resolved = resolveCodeToolType(codeType);
    return resolved;
  }
  const zcfConfig = readZcfConfig();
  if (zcfConfig?.codeToolType && isCodeToolType(zcfConfig.codeToolType)) {
    return zcfConfig.codeToolType;
  }
  return DEFAULT_CODE_TOOL_TYPE;
}
function syncMyclaudeStateIfNeeded(codeType, currentProfileId) {
  if (codeType !== "clavue") {
    return;
  }
  if (currentProfileId !== void 0) {
    setMyclaudeActiveProviderProfile(currentProfileId);
  }
  syncMyclaudeProviderProfilesFromClaudeConfig(ClaudeCodeConfigManager.readConfig());
}
async function handleList(codeType) {
  const targetCodeType = resolveCodeType(codeType);
  if (targetCodeType === "claude-code" || targetCodeType === "clavue") {
    await listClaudeCodeProfiles();
  } else if (targetCodeType === "codex") {
    await listCodexProvidersWithDisplay();
  }
}
async function listCodexProvidersWithDisplay() {
  const providers = await listCodexProviders();
  const existingConfig = readCodexConfig();
  const currentProvider = existingConfig?.modelProvider;
  const isCommented = existingConfig?.modelProviderCommented;
  if (!providers || providers.length === 0) {
    console.log(a.yellow(i18n.t("codex:noProvidersAvailable")));
    return;
  }
  console.log(a.bold(i18n.t("codex:listProvidersTitle")));
  console.log();
  if (currentProvider && !isCommented) {
    console.log(a.green(i18n.t("codex:currentProvider", { provider: currentProvider })));
    console.log();
  }
  providers.forEach((provider) => {
    const isCurrent = currentProvider === provider.id && !isCommented;
    const status = isCurrent ? a.green("\u25CF ") : "  ";
    const current = isCurrent ? a.yellow(` (${i18n.t("common:current")})`) : "";
    console.log(`${status}${a.white(provider.name)}${current}`);
    console.log(`    ${a.green(`ID: ${provider.id}`)} ${a.gray(`(${provider.baseUrl})`)}`);
    if (provider.tempEnvKey) {
      console.log(`    ${a.gray(`Env: ${provider.tempEnvKey}`)}`);
    }
    console.log();
  });
}
async function listClaudeCodeProfiles() {
  const config = ClaudeCodeConfigManager.readConfig();
  if (!config || !config.profiles || Object.keys(config.profiles).length === 0) {
    console.log(a.yellow(i18n.t("multi-config:noClaudeCodeProfilesAvailable")));
    return;
  }
  console.log(a.bold(i18n.t("multi-config:availableClaudeCodeProfiles")));
  console.log();
  const currentProfileId = config.currentProfileId;
  Object.values(config.profiles).forEach((profile) => {
    const isCurrent = profile.id === currentProfileId;
    const status = isCurrent ? a.green("\u25CF ") : "  ";
    const current = isCurrent ? a.yellow(i18n.t("common:current")) : "";
    console.log(`${status}${a.white(profile.name)}${current}`);
    console.log(`    ${a.green(`ID: ${profile.id}`)} ${a.gray(`(${profile.authType})`)}`);
    console.log();
  });
}
async function handleDirectSwitch(codeType, target) {
  const resolvedCodeType = resolveCodeType(codeType);
  if (resolvedCodeType === "claude-code" || resolvedCodeType === "clavue") {
    await handleClaudeCodeDirectSwitch(target, resolvedCodeType);
  } else if (resolvedCodeType === "codex") {
    if (target === "official") {
      await switchToOfficialLogin();
    } else {
      await switchToProvider(target);
    }
  }
}
async function handleClaudeCodeDirectSwitch(target, codeType = "claude-code") {
  if (target === "official") {
    const result = await ClaudeCodeConfigManager.switchToOfficial();
    if (result.success) {
      try {
        await ClaudeCodeConfigManager.applyProfileSettings(null);
        syncMyclaudeStateIfNeeded(codeType, "");
        console.log(a.green(i18n.t("multi-config:successfullySwitchedToOfficial")));
      } catch (error) {
        const reason = error instanceof Error ? error.message : String(error);
        console.log(a.red(reason));
      }
    } else {
      console.log(a.red(i18n.t("multi-config:failedToSwitchToOfficial", { error: result.error })));
    }
  } else if (target === "ccr") {
    const result = await ClaudeCodeConfigManager.switchToCcr();
    if (result.success) {
      try {
        const profile = ClaudeCodeConfigManager.getProfileById("ccr-proxy");
        await ClaudeCodeConfigManager.applyProfileSettings(profile);
        syncMyclaudeStateIfNeeded(codeType, "ccr-proxy");
        console.log(a.green(i18n.t("multi-config:successfullySwitchedToCcr")));
      } catch (error) {
        const reason = error instanceof Error ? error.message : String(error);
        console.log(a.red(reason));
      }
    } else {
      console.log(a.red(i18n.t("multi-config:failedToSwitchToCcr", { error: result.error })));
    }
  } else {
    const config = ClaudeCodeConfigManager.readConfig();
    if (!config || !config.profiles || Object.keys(config.profiles).length === 0) {
      console.log(a.yellow(i18n.t("multi-config:noClaudeCodeProfilesAvailable")));
      return;
    }
    const normalizedTarget = target.trim();
    let resolvedId = normalizedTarget;
    let resolvedProfile = config.profiles[normalizedTarget];
    if (!resolvedProfile) {
      const match = Object.entries(config.profiles).find(([, profile]) => profile.name === normalizedTarget);
      if (match) {
        resolvedId = match[0];
        resolvedProfile = match[1];
      }
    }
    if (!resolvedProfile) {
      console.log(a.red(i18n.t("multi-config:profileNameNotFound", { name: target })));
      return;
    }
    const result = await ClaudeCodeConfigManager.switchProfile(resolvedId);
    if (result.success) {
      try {
        await ClaudeCodeConfigManager.applyProfileSettings({ ...resolvedProfile, id: resolvedId });
        syncMyclaudeStateIfNeeded(codeType, resolvedId);
        console.log(a.green(i18n.t("multi-config:successfullySwitchedToProfile", { name: resolvedProfile.name })));
      } catch (error) {
        const reason = error instanceof Error ? error.message : String(error);
        console.log(a.red(reason));
      }
    } else {
      console.log(a.red(i18n.t("multi-config:failedToSwitchToProfile", { error: result.error })));
    }
  }
}
async function handleInteractiveSwitch(codeType) {
  const resolvedCodeType = resolveCodeType(codeType);
  if (resolvedCodeType === "claude-code" || resolvedCodeType === "clavue") {
    await handleClaudeCodeInteractiveSwitch(resolvedCodeType);
  } else if (resolvedCodeType === "codex") {
    await handleCodexInteractiveSwitch();
  }
}
async function handleClaudeCodeInteractiveSwitch(codeType = "claude-code") {
  const config = ClaudeCodeConfigManager.readConfig();
  if (!config || !config.profiles || Object.keys(config.profiles).length === 0) {
    console.log(a.yellow(i18n.t("multi-config:noClaudeCodeProfilesAvailable")));
    return;
  }
  const currentProfileId = config.currentProfileId;
  const createClaudeCodeChoices = (profiles, currentProfileId2) => {
    const choices2 = [];
    const isOfficialMode = !currentProfileId2 || currentProfileId2 === "official";
    choices2.push({
      name: isOfficialMode ? `${a.green("\u25CF ")}${i18n.t("codex:useOfficialLogin")} ${a.yellow(`(${i18n.t("common:current")})`)}` : `  ${i18n.t("codex:useOfficialLogin")}`,
      value: "official"
    });
    const isCcrMode = currentProfileId2 === "ccr-proxy";
    choices2.push({
      name: isCcrMode ? `${a.green("\u25CF ")}${i18n.t("multi-config:ccrProxyOption")} ${a.yellow(`(${i18n.t("common:current")})`)}` : `  ${i18n.t("multi-config:ccrProxyOption")}`,
      value: "ccr"
    });
    Object.values(profiles).filter((profile) => profile.id !== "ccr-proxy").forEach((profile) => {
      const isCurrent = profile.id === currentProfileId2;
      choices2.push({
        name: isCurrent ? `${a.green("\u25CF ")}${profile.name} ${a.yellow("(current)")}` : `  ${profile.name}`,
        value: profile.id
      });
    });
    return choices2;
  };
  const choices = createClaudeCodeChoices(config.profiles, currentProfileId);
  try {
    const { selectedConfig } = await inquirer.prompt([{
      type: "list",
      name: "selectedConfig",
      message: i18n.t("multi-config:selectClaudeCodeConfiguration"),
      choices: addNumbersToChoices(choices)
    }]);
    if (!selectedConfig) {
      console.log(a.yellow(i18n.t("multi-config:cancelled")));
      return;
    }
    await handleClaudeCodeDirectSwitch(selectedConfig, codeType);
  } catch (error) {
    if (error.name === "ExitPromptError") {
      console.log(a.green(`
${i18n.t("common:goodbye")}`));
      return;
    }
    throw error;
  }
}
async function handleCodexInteractiveSwitch() {
  const providers = await listCodexProviders();
  if (!providers || providers.length === 0) {
    console.log(a.yellow(i18n.t("codex:noProvidersAvailable")));
    return;
  }
  const existingConfig = readCodexConfig();
  const currentProvider = existingConfig?.modelProvider;
  const isCommented = existingConfig?.modelProviderCommented;
  const createApiConfigChoices = (providers2, currentProvider2, isCommented2) => {
    const choices2 = [];
    const isOfficialMode = !currentProvider2 || isCommented2;
    choices2.push({
      name: isOfficialMode ? `${a.green("\u25CF ")}${i18n.t("codex:useOfficialLogin")} ${a.yellow("(\u5F53\u524D)")}` : `  ${i18n.t("codex:useOfficialLogin")}`,
      value: "official"
    });
    providers2.forEach((provider) => {
      const isCurrent = currentProvider2 === provider.id && !isCommented2;
      choices2.push({
        name: isCurrent ? `${a.green("\u25CF ")}${provider.name} - ${a.gray(provider.id)} ${a.yellow("(\u5F53\u524D)")}` : `  ${provider.name} - ${a.gray(provider.id)}`,
        value: provider.id
      });
    });
    return choices2;
  };
  const choices = createApiConfigChoices(providers, currentProvider, isCommented);
  try {
    const { selectedConfig } = await inquirer.prompt([{
      type: "list",
      name: "selectedConfig",
      message: i18n.t("codex:apiConfigSwitchPrompt"),
      choices: addNumbersToChoices(choices)
    }]);
    if (!selectedConfig) {
      console.log(a.yellow(i18n.t("common:cancelled")));
      return;
    }
    let success = false;
    if (selectedConfig === "official") {
      success = await switchToOfficialLogin();
    } else {
      success = await switchToProvider(selectedConfig);
    }
    if (!success) {
      console.log(a.red(i18n.t("common:operationFailed")));
    }
  } catch (error) {
    if (error.name === "ExitPromptError") {
      console.log(a.green(`
${i18n.t("common:goodbye")}`));
      return;
    }
    throw error;
  }
}

export { configSwitchCommand };
