import a from './index5.mjs';
import { i as inquirer } from './index6.mjs';
import { ensureI18nInitialized, i18n } from './index2.mjs';
import { readZcfConfig } from './ccjk-config.mjs';
import { C as ClaudeCodeConfigManager } from './clavue-config.mjs';
import { r as resolveClaudeFamilyModelSlots } from '../shared/ccjk.B2U7DsPy.mjs';
import { a as addNumbersToChoices } from '../shared/ccjk.BFQ7yr5S.mjs';
import { p as promptBoolean } from '../shared/ccjk.DZ2LLOa-.mjs';
import { v as validateApiKey } from '../shared/ccjk.L7yC58_i.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:fs';
import 'node:url';
import '../shared/ccjk.bQ7Dh1g4.mjs';
import '../shared/ccjk.BBtCGd_g.mjs';
import './index3.mjs';
import './constants.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 '../shared/ccjk.DeWpAShp.mjs';
import '../shared/ccjk.C0WLUnFV.mjs';

function getAuthTypeLabel(authType) {
  ensureI18nInitialized();
  switch (authType) {
    case "api_key":
      return i18n.t("multi-config:authType.api_key");
    case "auth_token":
      return i18n.t("multi-config:authType.auth_token");
    case "ccr_proxy":
      return i18n.t("multi-config:authType.ccr_proxy");
    default:
      return authType;
  }
}
async function syncMyclaudeProfilesIfNeeded() {
  const zcfConfig = readZcfConfig();
  if (zcfConfig?.codeToolType !== "clavue") {
    return;
  }
  const { syncMyclaudeProviderProfilesFromCurrentClaudeConfig } = await import('./clavue-config.mjs').then(function (n) { return n.g; });
  syncMyclaudeProviderProfilesFromCurrentClaudeConfig();
}
async function configureIncrementalManagement() {
  ensureI18nInitialized();
  const zcfConfig = readZcfConfig();
  const runtimeLabel = zcfConfig?.codeToolType === "clavue" ? "Clavue" : "Claude Code";
  const config = ClaudeCodeConfigManager.readConfig();
  if (!config || !config.profiles || Object.keys(config.profiles).length === 0) {
    await handleAddProfile();
    if (!isClavueRuntime()) {
      await syncMyclaudeProfilesIfNeeded();
    }
    return;
  }
  const profiles = Object.values(config.profiles);
  const currentProfile = config.currentProfileId ? config.profiles[config.currentProfileId] : null;
  console.log(a.green(i18n.t("multi-config:incrementalManagementTitle", { runtime: runtimeLabel })));
  console.log(a.gray(i18n.t("multi-config:currentProfileCount", { count: profiles.length })));
  if (currentProfile) {
    console.log(a.gray(i18n.t("multi-config:currentDefaultProfile", { profile: currentProfile.name })));
  }
  const choices = [
    { name: i18n.t("multi-config:addProfile"), value: "add" },
    { name: i18n.t("multi-config:editProfile"), value: "edit" },
    { name: i18n.t("multi-config:copyProfile"), value: "copy" },
    { name: i18n.t("multi-config:deleteProfile"), value: "delete" },
    { name: i18n.t("common:skip"), value: "skip" }
  ];
  const { action } = await inquirer.prompt([{
    type: "list",
    name: "action",
    message: i18n.t("multi-config:selectAction"),
    choices: addNumbersToChoices(choices)
  }]);
  if (!action || action === "skip") {
    console.log(a.yellow(i18n.t("common:skip")));
    return;
  }
  switch (action) {
    case "add":
      await handleAddProfile();
      break;
    case "edit":
      await handleEditProfile(profiles);
      break;
    case "copy":
      await handleCopyProfile(profiles);
      break;
    case "delete":
      await handleDeleteProfile(profiles);
      break;
  }
  await syncMyclaudeProfilesIfNeeded();
}
async function promptContinueAdding() {
  return await promptBoolean({
    message: i18n.t("multi-config:addAnotherProfilePrompt"),
    defaultValue: false
  });
}
async function addProfileDirect() {
  ensureI18nInitialized();
  await handleAddProfile();
  if (!isClavueRuntime()) {
    await syncMyclaudeProfilesIfNeeded();
  }
}
function getProviderDefaultModels(provider) {
  return resolveClaudeFamilyModelSlots({
    defaultModels: provider?.claudeCode?.defaultModels
  });
}
function isClavueRuntime() {
  return readZcfConfig()?.codeToolType === "clavue";
}
function getDefaultModelsForRouteMode(mode, provider) {
  if (mode === "official") {
    return {
      primaryModel: "claude-sonnet-4-6",
      haikuModel: "claude-haiku-4-5-20251001",
      sonnetModel: "claude-sonnet-4-6",
      opusModel: "claude-opus-4-6"
    };
  }
  if (mode === "openai-native") {
    if (provider?.claudeCode?.defaultModels?.length) {
      const defaults = getProviderDefaultModels(provider);
      return {
        primaryModel: defaults.primaryModel || "gpt-5-codex",
        haikuModel: defaults.haikuModel || defaults.primaryModel || "gpt-5-codex",
        sonnetModel: defaults.sonnetModel || defaults.primaryModel || "gpt-5-codex",
        opusModel: defaults.opusModel || defaults.primaryModel || "gpt-5-codex"
      };
    }
    return resolveClaudeFamilyModelSlots({ selectedModel: "gpt-5-codex" });
  }
  return {
    primaryModel: "gpt-5-codex",
    haikuModel: "claude-haiku-4-5-20251001",
    sonnetModel: "gpt-5-codex",
    opusModel: "claude-opus-4-6"
  };
}
function toLegacyProviderMode(mode) {
  return mode === "openai-native" ? "openai-native" : mode === "ccr-proxy" ? "ccr-proxy" : "official";
}
async function promptModelRouteSelection(provider) {
  const isZh = i18n.language === "zh-CN";
  const { mode } = await inquirer.prompt([{
    type: "list",
    name: "mode",
    message: isZh ? "\u8BF7\u9009\u62E9\u6A21\u578B\u8DEF\u7531\u6A21\u5F0F:" : "Select model routing mode:",
    choices: addNumbersToChoices([
      {
        name: isZh ? "OpenAI / GPT \u6A21\u578B\uFF08GPT-5.x\u3001Codex\uFF09" : "OpenAI / GPT models (GPT-5.x, Codex)",
        value: "openai-native"
      },
      {
        name: isZh ? "Claude \u6A21\u578B\uFF08Anthropic / Claude \u517C\u5BB9\uFF09" : "Claude models (Anthropic / Claude compatible)",
        value: "official"
      },
      {
        name: isZh ? "\u6DF7\u5408\u6A21\u578B\uFF08OpenAI + Claude \u5206\u69FD\uFF09" : "Hybrid models (OpenAI + Claude slots)",
        value: "ccr-proxy"
      }
    ]),
    default: "openai-native"
  }]);
  const defaults = getDefaultModelsForRouteMode(mode, provider);
  const { promptCustomModels } = await import('./features.mjs');
  const models = await promptCustomModels(
    defaults.primaryModel,
    defaults.haikuModel,
    defaults.sonnetModel,
    defaults.opusModel
  );
  return { mode: toLegacyProviderMode(mode), models };
}
function toMyclaudeProviderProfile(profile, routeSelection) {
  return {
    id: profile.id || ClaudeCodeConfigManager.generateProfileId(profile.name),
    name: profile.name,
    provider: profile.provider || "custom",
    apiKey: profile.apiKey,
    baseUrl: profile.baseUrl,
    model: profile.primaryModel,
    fastModel: profile.defaultHaikuModel,
    authType: profile.authType,
    primaryModel: profile.primaryModel,
    defaultHaikuModel: profile.defaultHaikuModel,
    defaultSonnetModel: profile.defaultSonnetModel,
    defaultOpusModel: profile.defaultOpusModel,
    mode: routeSelection.mode
  };
}
function fromClavueProviderProfile(profile) {
  const routing = profile.modelRouting;
  return {
    id: profile.provenance?.kind === "imported" && profile.provenance.sourceId === "ccjk" && typeof profile.provenance.externalProfileId === "string" ? profile.provenance.externalProfileId : profile.id,
    name: profile.name,
    provider: profile.providerId || "custom",
    baseUrl: profile.baseUrl,
    authType: profile.authType,
    model: routing?.primaryModel,
    fastModel: routing?.smallFastModel,
    primaryModel: routing?.primaryModel,
    defaultHaikuModel: routing?.smallFastModel,
    defaultSonnetModel: routing?.generalModel || routing?.subagentModel,
    defaultOpusModel: routing?.planModel,
    mode: profile.modelMode === "openai_native" ? "openai-native" : profile.modelMode === "hybrid_compatible" ? "ccr-proxy" : "official"
  };
}
async function saveClavueNativeProfile(profile, routeSelection, setAsDefault) {
  const { readClavueConfig, setMyclaudeProviderProfiles } = await import('./clavue-config.mjs').then(function (n) { return n.g; });
  const config = readClavueConfig();
  const activeClavueProfileId = config?.clavueActiveProviderProfileId;
  const existingManagedProfiles = (config?.clavueProviderProfiles || []).filter((existing) => existing.provenance?.kind === "imported" && existing.provenance.sourceId === "ccjk").map(fromClavueProviderProfile);
  const activeManagedProfileId = existingManagedProfiles.find((existing) => {
    return existing.id === activeClavueProfileId || `ccjk-${existing.id}` === activeClavueProfileId;
  })?.id;
  const nextProfile = toMyclaudeProviderProfile(profile, routeSelection);
  const profiles = [
    ...existingManagedProfiles.filter((existing) => existing.id !== nextProfile.id),
    nextProfile
  ];
  setMyclaudeProviderProfiles(profiles, setAsDefault ? nextProfile.id : activeManagedProfileId || activeClavueProfileId);
}
async function handleAddProfile() {
  console.log(a.green(`
${i18n.t("multi-config:addingNewProfile")}`));
  const { getApiProviders } = await import('./api-providers.mjs');
  const providers = getApiProviders("claude-code");
  const providerChoices = [
    { name: i18n.t("api:customProvider"), value: "custom" },
    ...providers.map((p) => ({ name: p.name, value: p.id }))
  ];
  const { selectedProvider } = await inquirer.prompt([{
    type: "list",
    name: "selectedProvider",
    message: i18n.t("api:selectApiProvider"),
    choices: addNumbersToChoices(providerChoices)
  }]);
  let prefilledBaseUrl;
  let prefilledAuthType;
  const selectedProviderPreset = selectedProvider !== "custom" ? providers.find((p) => p.id === selectedProvider) : void 0;
  if (selectedProviderPreset?.claudeCode) {
    prefilledBaseUrl = selectedProviderPreset.claudeCode.baseUrl;
    prefilledAuthType = selectedProviderPreset.claudeCode.authType;
    console.log(a.gray(i18n.t("api:providerSelected", { name: selectedProviderPreset.name })));
  }
  const answers = await inquirer.prompt([
    {
      type: "input",
      name: "profileName",
      message: i18n.t("multi-config:profileNamePrompt"),
      default: selectedProviderPreset?.name,
      validate: (input) => {
        const trimmed = input.trim();
        if (!trimmed) {
          return i18n.t("multi-config:profileNameRequired");
        }
        if (!/^[\w\-\s.\u4E00-\u9FA5]+$/.test(trimmed)) {
          return i18n.t("multi-config:profileNameInvalid");
        }
        return true;
      }
    },
    {
      type: "list",
      name: "authType",
      message: i18n.t("multi-config:authTypePrompt"),
      choices: [
        { name: i18n.t("multi-config:authType.api_key"), value: "api_key" },
        { name: i18n.t("multi-config:authType.auth_token"), value: "auth_token" }
      ],
      default: prefilledAuthType || "api_key",
      when: () => selectedProvider === "custom"
      // Only ask if custom
    },
    {
      type: "input",
      name: "baseUrl",
      message: i18n.t("multi-config:baseUrlPrompt"),
      default: prefilledBaseUrl || "https://api.anthropic.com",
      when: (answers2) => selectedProvider === "custom" && answers2.authType !== "ccr_proxy",
      validate: (input) => {
        const trimmed = input.trim();
        if (!trimmed) {
          return i18n.t("multi-config:baseUrlRequired");
        }
        try {
          new URL(trimmed);
          return true;
        } catch {
          return i18n.t("multi-config:baseUrlInvalid");
        }
      }
    },
    {
      type: "input",
      name: "apiKey",
      message: selectedProvider !== "custom" ? i18n.t("api:enterProviderApiKey", { provider: selectedProviderPreset?.name || selectedProvider }) : i18n.t("multi-config:apiKeyPrompt"),
      when: (answers2) => selectedProvider === "custom" ? answers2.authType !== "ccr_proxy" : true,
      validate: (input) => {
        const trimmed = input.trim();
        if (!trimmed) {
          return i18n.t("multi-config:apiKeyRequired");
        }
        const validation = validateApiKey(trimmed);
        if (!validation.isValid) {
          return validation.error || "Invalid API key format";
        }
        return true;
      }
    }
  ]);
  const routeSelection = await promptModelRouteSelection(selectedProviderPreset);
  const modelConfig = routeSelection.models;
  const setAsDefault = await promptBoolean({
    message: i18n.t("multi-config:setAsDefaultPrompt"),
    defaultValue: true
  });
  const profileName = answers.profileName.trim();
  const profileId = ClaudeCodeConfigManager.generateProfileId(profileName);
  const profile = {
    id: profileId,
    name: profileName,
    authType: selectedProvider === "custom" ? answers.authType : prefilledAuthType,
    provider: selectedProvider
  };
  if (profile.authType !== "ccr_proxy") {
    profile.apiKey = answers.apiKey.trim();
    profile.baseUrl = selectedProvider === "custom" ? answers.baseUrl.trim() : prefilledBaseUrl;
  }
  if (modelConfig) {
    if (modelConfig.primaryModel.trim()) {
      profile.primaryModel = modelConfig.primaryModel.trim();
    }
    if (modelConfig.haikuModel.trim())
      profile.defaultHaikuModel = modelConfig.haikuModel.trim();
    if (modelConfig.sonnetModel.trim())
      profile.defaultSonnetModel = modelConfig.sonnetModel.trim();
    if (modelConfig.opusModel.trim())
      profile.defaultOpusModel = modelConfig.opusModel.trim();
  }
  if (isClavueRuntime()) {
    await saveClavueNativeProfile(profile, routeSelection, setAsDefault);
    console.log(a.green(i18n.t("multi-config:profileAdded", { name: profile.name })));
  } else {
    const existingProfile = ClaudeCodeConfigManager.getProfileByName(profile.name);
    if (existingProfile) {
      const overwrite = await promptBoolean({
        message: i18n.t("multi-config:profileDuplicatePrompt", {
          name: profile.name,
          source: i18n.t("multi-config:existingConfig")
        }),
        defaultValue: false
      });
      if (!overwrite) {
        console.log(a.yellow(i18n.t("multi-config:profileDuplicateSkipped", { name: profile.name })));
        const shouldContinue2 = await promptContinueAdding();
        if (shouldContinue2) {
          await handleAddProfile();
        }
        return;
      }
      const updateResult = await ClaudeCodeConfigManager.updateProfile(existingProfile.id, {
        name: profile.name,
        authType: profile.authType,
        provider: profile.provider,
        apiKey: profile.apiKey,
        baseUrl: profile.baseUrl,
        primaryModel: profile.primaryModel,
        defaultHaikuModel: profile.defaultHaikuModel,
        defaultSonnetModel: profile.defaultSonnetModel,
        defaultOpusModel: profile.defaultOpusModel
      });
      if (updateResult.success) {
        console.log(a.green(i18n.t("multi-config:profileUpdated", { name: profile.name })));
        if (updateResult.backupPath) {
          console.log(a.gray(i18n.t("common:backupCreated", { path: updateResult.backupPath })));
        }
        if (setAsDefault) {
          const switchResult = await ClaudeCodeConfigManager.switchProfile(existingProfile.id);
          if (switchResult.success) {
            console.log(a.green(i18n.t("multi-config:profileSetAsDefault", { name: profile.name })));
            await ClaudeCodeConfigManager.applyProfileSettings({ ...profile, id: existingProfile.id });
          }
        }
      } else {
        console.log(a.red(i18n.t("multi-config:profileUpdateFailed", { error: updateResult.error || "" })));
      }
    } else {
      const result = await ClaudeCodeConfigManager.addProfile(profile);
      if (result.success) {
        const runtimeProfile = result.addedProfile || { ...profile, id: profileId };
        console.log(a.green(i18n.t("multi-config:profileAdded", { name: runtimeProfile.name })));
        if (result.backupPath) {
          console.log(a.gray(i18n.t("common:backupCreated", { path: result.backupPath })));
        }
        if (setAsDefault) {
          const switchResult = await ClaudeCodeConfigManager.switchProfile(runtimeProfile.id);
          if (switchResult.success) {
            console.log(a.green(i18n.t("multi-config:profileSetAsDefault", { name: runtimeProfile.name })));
            await ClaudeCodeConfigManager.applyProfileSettings(runtimeProfile);
          }
        }
      } else {
        console.log(a.red(i18n.t("multi-config:profileAddFailed", { error: result.error })));
      }
    }
  }
  const shouldContinue = await promptContinueAdding();
  if (shouldContinue) {
    await handleAddProfile();
  }
}
async function handleEditProfile(profiles) {
  const choices = profiles.map((profile) => ({
    name: `${profile.name} (${getAuthTypeLabel(profile.authType)})`,
    value: profile.id
  }));
  const { selectedProfileId } = await inquirer.prompt([{
    type: "list",
    name: "selectedProfileId",
    message: i18n.t("multi-config:selectProfileToEdit"),
    choices: addNumbersToChoices(choices)
  }]);
  if (!selectedProfileId) {
    console.log(a.yellow(i18n.t("common:cancelled")));
    return;
  }
  const selectedProfile = profiles.find((p) => p.id === selectedProfileId);
  if (!selectedProfile) {
    console.log(a.red(i18n.t("multi-config:profileNotFound")));
    return;
  }
  console.log(a.green(`
${i18n.t("multi-config:editingProfile", { name: selectedProfile.name })}`));
  const answers = await inquirer.prompt([
    {
      type: "input",
      name: "profileName",
      message: i18n.t("multi-config:profileNamePrompt"),
      default: selectedProfile.name,
      validate: (input) => {
        const trimmed = input.trim();
        if (!trimmed) {
          return i18n.t("multi-config:profileNameRequired");
        }
        if (!/^[\w\-\s\u4E00-\u9FA5]+$/.test(trimmed)) {
          return i18n.t("multi-config:profileNameInvalid");
        }
        return true;
      }
    },
    {
      type: "input",
      name: "baseUrl",
      message: i18n.t("multi-config:baseUrlPrompt"),
      default: selectedProfile.baseUrl || "https://api.anthropic.com",
      when: () => selectedProfile.authType !== "ccr_proxy",
      validate: (input) => {
        const trimmed = input.trim();
        if (!trimmed) {
          return i18n.t("multi-config:baseUrlRequired");
        }
        try {
          new URL(trimmed);
          return true;
        } catch {
          return i18n.t("multi-config:baseUrlInvalid");
        }
      }
    },
    {
      type: "input",
      name: "apiKey",
      message: i18n.t("multi-config:apiKeyPrompt"),
      default: selectedProfile.apiKey,
      when: () => selectedProfile.authType !== "ccr_proxy",
      validate: (input) => {
        const trimmed = input.trim();
        if (!trimmed) {
          return i18n.t("multi-config:apiKeyRequired");
        }
        const validation = validateApiKey(trimmed);
        if (!validation.isValid) {
          return validation.error || "Invalid API key format";
        }
        return true;
      }
    }
  ]);
  let modelConfig = null;
  if (selectedProfile.authType !== "ccr_proxy") {
    const { promptCustomModels } = await import('./features.mjs');
    modelConfig = await promptCustomModels(
      selectedProfile.primaryModel,
      selectedProfile.defaultHaikuModel,
      selectedProfile.defaultSonnetModel,
      selectedProfile.defaultOpusModel
    );
  }
  const updateData = {
    name: answers.profileName.trim()
  };
  if (selectedProfile.authType !== "ccr_proxy") {
    updateData.apiKey = answers.apiKey.trim();
    updateData.baseUrl = answers.baseUrl.trim();
    if (modelConfig) {
      if (modelConfig.primaryModel.trim()) {
        updateData.primaryModel = modelConfig.primaryModel.trim();
      }
      if (modelConfig.haikuModel.trim())
        updateData.defaultHaikuModel = modelConfig.haikuModel.trim();
      if (modelConfig.sonnetModel.trim())
        updateData.defaultSonnetModel = modelConfig.sonnetModel.trim();
      if (modelConfig.opusModel.trim())
        updateData.defaultOpusModel = modelConfig.opusModel.trim();
    }
  }
  const result = await ClaudeCodeConfigManager.updateProfile(selectedProfile.id, updateData);
  if (result.success) {
    console.log(a.green(i18n.t("multi-config:profileUpdated", { name: updateData.name })));
    if (result.backupPath) {
      console.log(a.gray(i18n.t("common:backupCreated", { path: result.backupPath })));
    }
    const updatedProfileId = result.updatedProfile?.id || ClaudeCodeConfigManager.generateProfileId(updateData.name);
    const switchResult = await ClaudeCodeConfigManager.switchProfile(updatedProfileId);
    if (switchResult.success) {
      const updatedProfile = ClaudeCodeConfigManager.getProfileById(updatedProfileId);
      if (updatedProfile) {
        console.log(a.green(i18n.t("multi-config:profileSetAsDefault", { name: updatedProfile.name })));
        console.log(a.green(i18n.t("multi-config:settingsApplied")));
      }
    } else {
      console.log(a.red(i18n.t("multi-config:failedToSwitchToProfile", { error: switchResult.error })));
    }
  } else {
    console.log(a.red(i18n.t("multi-config:profileUpdateFailed", { error: result.error })));
  }
}
async function handleCopyProfile(profiles) {
  const choices = profiles.map((profile) => ({
    name: `${profile.name} (${getAuthTypeLabel(profile.authType)})`,
    value: profile.id
  }));
  const { selectedProfileId } = await inquirer.prompt([{
    type: "list",
    name: "selectedProfileId",
    message: i18n.t("multi-config:selectProfileToCopy"),
    choices: addNumbersToChoices(choices)
  }]);
  if (!selectedProfileId) {
    console.log(a.yellow(i18n.t("common:cancelled")));
    return;
  }
  const selectedProfile = profiles.find((p) => p.id === selectedProfileId);
  if (!selectedProfile) {
    console.log(a.red(i18n.t("multi-config:profileNotFound")));
    return;
  }
  console.log(a.green(`
${i18n.t("multi-config:copyingProfile", { name: selectedProfile.name })}`));
  const copiedName = `${selectedProfile.name}-copy`;
  const questions = [
    {
      type: "input",
      name: "profileName",
      message: i18n.t("multi-config:profileNamePrompt"),
      default: copiedName,
      validate: (input) => {
        const trimmed = input.trim();
        if (!trimmed) {
          return i18n.t("multi-config:profileNameRequired");
        }
        if (!/^[\w\-\s.\u4E00-\u9FA5]+$/.test(trimmed)) {
          return i18n.t("multi-config:profileNameInvalid");
        }
        return true;
      }
    }
  ];
  if (selectedProfile.authType !== "ccr_proxy") {
    questions.push(
      {
        type: "input",
        name: "baseUrl",
        message: i18n.t("multi-config:baseUrlPrompt"),
        default: selectedProfile.baseUrl || "https://api.anthropic.com",
        validate: (input) => {
          const trimmed = input.trim();
          if (!trimmed) {
            return i18n.t("multi-config:baseUrlRequired");
          }
          try {
            new URL(trimmed);
            return true;
          } catch {
            return i18n.t("multi-config:baseUrlInvalid");
          }
        }
      },
      {
        type: "input",
        name: "apiKey",
        message: i18n.t("multi-config:apiKeyPrompt"),
        default: selectedProfile.apiKey,
        validate: (input) => {
          const trimmed = input.trim();
          if (!trimmed) {
            return i18n.t("multi-config:apiKeyRequired");
          }
          const validation = validateApiKey(trimmed);
          if (!validation.isValid) {
            return validation.error || "Invalid API key format";
          }
          return true;
        }
      }
    );
  }
  const answers = await inquirer.prompt(questions);
  let modelConfig = null;
  if (selectedProfile.authType !== "ccr_proxy") {
    const { promptCustomModels } = await import('./features.mjs');
    modelConfig = await promptCustomModels(
      selectedProfile.primaryModel,
      selectedProfile.defaultHaikuModel,
      selectedProfile.defaultSonnetModel,
      selectedProfile.defaultOpusModel
    );
  }
  const setAsDefault = await promptBoolean({
    message: i18n.t("multi-config:setAsDefaultPrompt"),
    defaultValue: false
  });
  const profileName = answers.profileName.trim();
  const profileId = ClaudeCodeConfigManager.generateProfileId(profileName);
  const copiedProfile = {
    id: profileId,
    name: profileName,
    authType: selectedProfile.authType
  };
  if (selectedProfile.authType !== "ccr_proxy") {
    copiedProfile.apiKey = answers.apiKey.trim();
    copiedProfile.baseUrl = answers.baseUrl.trim();
    if (modelConfig) {
      if (modelConfig.primaryModel.trim()) {
        copiedProfile.primaryModel = modelConfig.primaryModel.trim();
      }
      if (modelConfig.haikuModel.trim())
        copiedProfile.defaultHaikuModel = modelConfig.haikuModel.trim();
      if (modelConfig.sonnetModel.trim())
        copiedProfile.defaultSonnetModel = modelConfig.sonnetModel.trim();
      if (modelConfig.opusModel.trim())
        copiedProfile.defaultOpusModel = modelConfig.opusModel.trim();
    }
  }
  const result = await ClaudeCodeConfigManager.addProfile(copiedProfile);
  if (result.success) {
    const runtimeProfile = result.addedProfile || { ...copiedProfile, id: profileId };
    console.log(a.green(i18n.t("multi-config:profileCopied", { name: runtimeProfile.name })));
    if (result.backupPath) {
      console.log(a.gray(i18n.t("common:backupCreated", { path: result.backupPath })));
    }
    if (setAsDefault) {
      const switchResult = await ClaudeCodeConfigManager.switchProfile(runtimeProfile.id);
      if (switchResult.success) {
        console.log(a.green(i18n.t("multi-config:profileSetAsDefault", { name: runtimeProfile.name })));
        await ClaudeCodeConfigManager.applyProfileSettings(runtimeProfile);
      }
    }
  } else {
    console.log(a.red(i18n.t("multi-config:profileCopyFailed", { error: result.error })));
  }
}
async function handleDeleteProfile(profiles) {
  if (profiles.length <= 1) {
    console.log(a.yellow(i18n.t("multi-config:cannotDeleteLast")));
    return;
  }
  const choices = profiles.map((profile) => ({
    name: `${profile.name} (${getAuthTypeLabel(profile.authType)})`,
    value: profile.id
  }));
  const { selectedProfileIds } = await inquirer.prompt({
    type: "checkbox",
    name: "selectedProfileIds",
    message: i18n.t("multi-config:selectProfilesToDelete"),
    choices: addNumbersToChoices(choices),
    validate: (input) => {
      if (input.length === 0) {
        return i18n.t("multi-config:selectAtLeastOne");
      }
      if (input.length >= profiles.length) {
        return i18n.t("multi-config:cannotDeleteAll");
      }
      return true;
    }
  });
  if (!selectedProfileIds || selectedProfileIds.length === 0) {
    console.log(a.yellow(i18n.t("common:cancelled")));
    return;
  }
  const selectedNames = selectedProfileIds.map(
    (id) => profiles.find((p) => p.id === id)?.name || id
  );
  const confirmed = await promptBoolean({
    message: i18n.t("multi-config:confirmDeleteProfiles", { providers: selectedNames.join(", ") }),
    defaultValue: false
  });
  if (!confirmed) {
    console.log(a.yellow(i18n.t("common:cancelled")));
    return;
  }
  const result = await ClaudeCodeConfigManager.deleteProfiles(selectedProfileIds);
  if (result.success) {
    console.log(a.green(i18n.t("multi-config:profilesDeleted", { count: selectedProfileIds.length })));
    if (result.backupPath) {
      console.log(a.gray(i18n.t("common:backupCreated", { path: result.backupPath })));
    }
    if (result.newCurrentProfileId) {
      const newProfile = ClaudeCodeConfigManager.getProfileById(result.newCurrentProfileId);
      if (newProfile) {
        console.log(a.green(i18n.t("multi-config:newDefaultProfile", { profile: newProfile.name })));
        await ClaudeCodeConfigManager.applyProfileSettings(newProfile);
      }
    }
  } else {
    console.log(a.red(i18n.t("multi-config:profilesDeleteFailed", { error: result.error })));
  }
}

export { addProfileDirect, configureIncrementalManagement, getAuthTypeLabel };
