import a from '../chunks/index5.mjs';
import { i as inquirer } from '../chunks/index6.mjs';
import { i18n } from '../chunks/index2.mjs';
import { b as getPresetById, c as getRecommendedPresets, a as getChinesePresets, g as getAllPresets } from './ccjk.DopKzo3z.mjs';
import { existsSync, readFileSync, mkdirSync } from 'node:fs';
import { homedir } from 'node:os';
import { writeFileAtomic } from '../chunks/fs-operations.mjs';
import { j as join } from './ccjk.bQ7Dh1g4.mjs';

const CLAUDE_DIR = join(homedir(), ".claude");
const SETTINGS_FILE = join(CLAUDE_DIR, "settings.json");
function readSettings() {
  if (!existsSync(SETTINGS_FILE)) {
    return {};
  }
  try {
    return JSON.parse(readFileSync(SETTINGS_FILE, "utf-8"));
  } catch {
    return {};
  }
}
function writeSettings(settings) {
  if (!existsSync(CLAUDE_DIR)) {
    mkdirSync(CLAUDE_DIR, { recursive: true });
  }
  writeFileAtomic(SETTINGS_FILE, JSON.stringify(settings, null, 2));
}
function configureSimpleMode(config) {
  try {
    const settings = readSettings();
    if (!settings.env) {
      settings.env = {};
    }
    delete settings.env.ANTHROPIC_AUTH_TOKEN;
    settings.env.ANTHROPIC_API_KEY = config.apiKey;
    settings.env.ANTHROPIC_BASE_URL = config.baseUrl;
    writeSettings(settings);
    return {
      success: true,
      mode: "simple",
      provider: config.provider,
      message: `API configured successfully for ${config.provider}`
    };
  } catch (error) {
    return {
      success: false,
      mode: "simple",
      error: error instanceof Error ? error.message : String(error)
    };
  }
}
function configureOfficialMode(apiKey) {
  try {
    const settings = readSettings();
    if (!settings.env) {
      settings.env = {};
    }
    delete settings.env.ANTHROPIC_BASE_URL;
    delete settings.env.ANTHROPIC_AUTH_TOKEN;
    settings.env.ANTHROPIC_API_KEY = apiKey;
    writeSettings(settings);
    return {
      success: true,
      mode: "official",
      provider: "anthropic",
      message: "Official Anthropic API configured successfully"
    };
  } catch (error) {
    return {
      success: false,
      mode: "official",
      error: error instanceof Error ? error.message : String(error)
    };
  }
}
function configureWithPreset(preset, apiKey) {
  if (preset.id === "anthropic") {
    return configureOfficialMode(apiKey);
  }
  return configureSimpleMode({
    mode: "simple",
    provider: preset.id,
    apiKey,
    baseUrl: preset.baseUrl,
    model: preset.defaultModel
  });
}
function getCurrentConfig() {
  try {
    const settings = readSettings();
    if (!settings.env) {
      return null;
    }
    return {
      ANTHROPIC_BASE_URL: settings.env.ANTHROPIC_BASE_URL,
      ANTHROPIC_API_KEY: settings.env.ANTHROPIC_API_KEY,
      ANTHROPIC_AUTH_TOKEN: settings.env.ANTHROPIC_AUTH_TOKEN
    };
  } catch {
    return null;
  }
}
function detectCurrentMode() {
  const config = getCurrentConfig();
  if (!config) {
    return { mode: "none" };
  }
  if (config.ANTHROPIC_BASE_URL?.includes("127.0.0.1:3456") || config.ANTHROPIC_BASE_URL?.includes("localhost:3456")) {
    return { mode: "ccr", provider: "ccr" };
  }
  if (!config.ANTHROPIC_BASE_URL || config.ANTHROPIC_BASE_URL.includes("api.anthropic.com")) {
    if (config.ANTHROPIC_AUTH_TOKEN) {
      return { mode: "official", provider: "anthropic-oauth" };
    }
    if (config.ANTHROPIC_API_KEY) {
      return { mode: "official", provider: "anthropic" };
    }
    return { mode: "none" };
  }
  const baseUrl = config.ANTHROPIC_BASE_URL.toLowerCase();
  let provider = "custom";
  if (baseUrl.includes("302.ai"))
    provider = "302ai";
  else if (baseUrl.includes("openrouter.ai"))
    provider = "openrouter";
  else if (baseUrl.includes("deepseek.com"))
    provider = "deepseek";
  else if (baseUrl.includes("dashscope.aliyuncs.com"))
    provider = "qwen";
  else if (baseUrl.includes("siliconflow.cn"))
    provider = "siliconflow";
  else if (baseUrl.includes("modelscope.cn"))
    provider = "modelscope";
  else if (baseUrl.includes("volces.com"))
    provider = "volcengine";
  else if (baseUrl.includes("moonshot.cn"))
    provider = "kimi";
  else if (baseUrl.includes("bigmodel.cn"))
    provider = "glm";
  else if (baseUrl.includes("generativelanguage.googleapis.com"))
    provider = "gemini";
  else if (baseUrl.includes("groq.com"))
    provider = "groq";
  else if (baseUrl.includes("localhost:11434"))
    provider = "ollama";
  return { mode: "simple", provider };
}
function validateApiKey(apiKey, provider) {
  if (!apiKey || apiKey.trim() === "") {
    return { valid: false, message: "API key is required" };
  }
  if (provider === "anthropic") {
    if (!apiKey.startsWith("sk-ant-")) {
      return { valid: false, message: "Anthropic API key should start with sk-ant-" };
    }
  }
  if (provider === "openrouter") {
    if (!apiKey.startsWith("sk-or-")) {
      return { valid: false, message: "OpenRouter API key should start with sk-or-" };
    }
  }
  return { valid: true };
}
function quickSetup(providerId, apiKey) {
  const preset = getPresetById(providerId);
  if (!preset) {
    return {
      success: false,
      mode: "simple",
      error: `Unknown provider: ${providerId}`
    };
  }
  if (preset.requiresApiKey) {
    const validation = validateApiKey(apiKey, providerId);
    if (!validation.valid) {
      return {
        success: false,
        mode: "simple",
        error: validation.message
      };
    }
  }
  return configureWithPreset(preset, apiKey);
}

function resolveApiRouterLang(lang) {
  const effectiveLang = lang || i18n.language;
  return typeof effectiveLang === "string" && effectiveLang.toLowerCase().startsWith("zh") ? "zh-CN" : "en";
}
function displayCurrentStatus(lang) {
  lang = resolveApiRouterLang(lang);
  const { mode, provider } = detectCurrentMode();
  const config = getCurrentConfig();
  console.log("");
  console.log(a.green("\u2550".repeat(50)));
  console.log(a.bold.cyan(lang === "zh-CN" ? "  \u5F53\u524D API \u914D\u7F6E" : "  Current API Configuration"));
  console.log(a.green("\u2550".repeat(50)));
  console.log("");
  if (mode === "none") {
    console.log(a.yellow(lang === "zh-CN" ? "  \u26A0 \u672A\u914D\u7F6E API" : "  \u26A0 No API configured"));
    console.log("");
    return;
  }
  const modeLabels = {
    official: lang === "zh-CN" ? "\u5B98\u65B9 Anthropic" : "Official Anthropic",
    simple: lang === "zh-CN" ? "\u7B80\u5355\u6A21\u5F0F (API \u4E2D\u8F6C)" : "Simple Mode (API Proxy)",
    ccr: lang === "zh-CN" ? "CCR \u9AD8\u7EA7\u8DEF\u7531" : "CCR Advanced Router"
  };
  console.log(`  ${a.bold(lang === "zh-CN" ? "\u6A21\u5F0F:" : "Mode:")} ${a.green(modeLabels[mode])}`);
  if (provider) {
    const preset = getPresetById(provider);
    const providerName = preset ? lang === "zh-CN" ? preset.nameZh : preset.name : provider;
    console.log(`  ${a.bold(lang === "zh-CN" ? "\u63D0\u4F9B\u5546:" : "Provider:")} ${a.green(providerName)}`);
  }
  if (config?.ANTHROPIC_BASE_URL) {
    console.log(`  ${a.bold("Base URL:")} ${a.gray(config.ANTHROPIC_BASE_URL)}`);
  }
  if (config?.ANTHROPIC_API_KEY) {
    const masked = `${config.ANTHROPIC_API_KEY.substring(0, 10)}...`;
    console.log(`  ${a.bold("API Key:")} ${a.gray(masked)}`);
  }
  console.log("");
}
async function runConfigWizard(lang) {
  lang = resolveApiRouterLang(lang);
  console.log("");
  console.log(a.green("\u2550".repeat(50)));
  console.log(a.bold.cyan(lang === "zh-CN" ? "  API \u914D\u7F6E\u5411\u5BFC" : "  API Configuration Wizard"));
  console.log(a.green("\u2550".repeat(50)));
  console.log("");
  const modeChoices = [
    {
      name: lang === "zh-CN" ? "1. \u81EA\u5B9A\u4E49\u914D\u7F6E - \u624B\u52A8\u8F93\u5165 API \u5730\u5740\u548C\u5BC6\u94A5" : "1. Custom Configuration - Manual API URL and key",
      value: "custom"
    },
    {
      name: lang === "zh-CN" ? "2. \u5B98\u65B9 Anthropic API - \u76F4\u63A5\u8FDE\u63A5 Anthropic" : "2. Official Anthropic API - Direct connection",
      value: "official"
    },
    {
      name: lang === "zh-CN" ? "3. CCR \u9AD8\u7EA7\u8DEF\u7531 - \u5B8C\u6574 Claude Code Router \u914D\u7F6E" : "3. CCR Advanced Router - Full Claude Code Router setup",
      value: "ccr"
    },
    {
      name: lang === "zh-CN" ? "4. \u5FEB\u901F\u914D\u7F6E (\u63A8\u8350) - \u9009\u62E9\u9884\u8BBE\u63D0\u4F9B\u5546" : "4. Quick Setup (Recommended) - Choose preset provider",
      value: "quick"
    }
  ];
  const { mode } = await inquirer.prompt({
    type: "list",
    name: "mode",
    message: lang === "zh-CN" ? "\u9009\u62E9\u914D\u7F6E\u6A21\u5F0F:" : "Select configuration mode:",
    choices: modeChoices
  });
  switch (mode) {
    case "quick":
      return await runQuickSetup(lang);
    case "official":
      return await runOfficialSetup(lang);
    case "custom":
      return await runCustomSetup(lang);
    case "ccr":
      return await runCcrSetup(lang);
    default:
      return { success: false, mode: "simple", error: "Unknown mode" };
  }
}
async function runQuickSetup(lang) {
  const recommended = getRecommendedPresets();
  const chinese = getChinesePresets().filter((p) => !recommended.find((r) => r.id === p.id));
  const all = getAllPresets();
  const choices = [
    new inquirer.Separator(lang === "zh-CN" ? "\u2500\u2500\u2500 \u63A8\u8350 \u2500\u2500\u2500" : "\u2500\u2500\u2500 Recommended \u2500\u2500\u2500"),
    ...recommended.map((p, i) => ({
      name: `${i + 1}. ${lang === "zh-CN" ? p.nameZh : p.name} - ${lang === "zh-CN" ? p.descriptionZh : p.description}`,
      value: p.id
    })),
    new inquirer.Separator(lang === "zh-CN" ? "\u2500\u2500\u2500 \u56FD\u5185\u670D\u52A1 \u2500\u2500\u2500" : "\u2500\u2500\u2500 Chinese Providers \u2500\u2500\u2500"),
    ...chinese.map((p, i) => ({
      name: `${recommended.length + i + 1}. ${lang === "zh-CN" ? p.nameZh : p.name} - ${lang === "zh-CN" ? p.descriptionZh : p.description}`,
      value: p.id
    })),
    new inquirer.Separator(lang === "zh-CN" ? "\u2500\u2500\u2500 \u66F4\u591A \u2500\u2500\u2500" : "\u2500\u2500\u2500 More \u2500\u2500\u2500"),
    {
      name: lang === "zh-CN" ? "\u67E5\u770B\u6240\u6709\u63D0\u4F9B\u5546..." : "View all providers...",
      value: "__all__"
    }
  ];
  const { providerId } = await inquirer.prompt({
    type: "list",
    name: "providerId",
    message: lang === "zh-CN" ? "\u9009\u62E9 API \u63D0\u4F9B\u5546:" : "Select API provider:",
    choices,
    pageSize: 15
  });
  let finalProviderId = providerId;
  if (providerId === "__all__") {
    const allChoices = all.map((p, i) => ({
      name: `${i + 1}. [${p.category}] ${lang === "zh-CN" ? p.nameZh : p.name}`,
      value: p.id
    }));
    const result2 = await inquirer.prompt({
      type: "list",
      name: "providerId",
      message: lang === "zh-CN" ? "\u9009\u62E9\u63D0\u4F9B\u5546:" : "Select provider:",
      choices: allChoices,
      pageSize: 20
    });
    finalProviderId = result2.providerId;
  }
  const preset = getPresetById(finalProviderId);
  if (!preset) {
    return { success: false, mode: "simple", error: "Provider not found" };
  }
  console.log("");
  console.log(a.green(`\u{1F4CB} ${lang === "zh-CN" ? preset.nameZh : preset.name}`));
  if (preset.instructions) {
    console.log(a.gray(`   ${lang === "zh-CN" ? preset.instructions.zh : preset.instructions.en}`));
  }
  console.log("");
  let apiKey = "";
  if (preset.requiresApiKey) {
    const { key } = await inquirer.prompt({
      type: "password",
      name: "key",
      message: lang === "zh-CN" ? "\u8F93\u5165 API \u5BC6\u94A5:" : "Enter API key:",
      mask: "*",
      validate: (value) => {
        if (!value)
          return lang === "zh-CN" ? "API \u5BC6\u94A5\u4E0D\u80FD\u4E3A\u7A7A" : "API key is required";
        return true;
      }
    });
    apiKey = key;
  }
  const result = configureWithPreset(preset, apiKey);
  if (result.success) {
    console.log("");
    console.log(a.green(`\u2714 ${lang === "zh-CN" ? "API \u914D\u7F6E\u6210\u529F!" : "API configured successfully!"}`));
    console.log(a.gray(`  ${lang === "zh-CN" ? "\u63D0\u4F9B\u5546:" : "Provider:"} ${lang === "zh-CN" ? preset.nameZh : preset.name}`));
    console.log(a.gray(`  ${lang === "zh-CN" ? "\u9ED8\u8BA4\u6A21\u578B:" : "Default model:"} ${preset.defaultModel}`));
    console.log("");
  }
  return result;
}
async function runOfficialSetup(lang) {
  console.log("");
  console.log(a.green(lang === "zh-CN" ? "\u{1F4CB} \u5B98\u65B9 Anthropic API" : "\u{1F4CB} Official Anthropic API"));
  console.log(a.gray(lang === "zh-CN" ? "   \u4ECE https://console.anthropic.com/settings/keys \u83B7\u53D6 API \u5BC6\u94A5" : "   Get your API key from https://console.anthropic.com/settings/keys"));
  console.log("");
  const { apiKey } = await inquirer.prompt({
    type: "password",
    name: "apiKey",
    message: lang === "zh-CN" ? "\u8F93\u5165 Anthropic API \u5BC6\u94A5:" : "Enter Anthropic API key:",
    mask: "*",
    validate: (value) => {
      if (!value)
        return lang === "zh-CN" ? "API \u5BC6\u94A5\u4E0D\u80FD\u4E3A\u7A7A" : "API key is required";
      if (!value.startsWith("sk-ant-")) {
        return lang === "zh-CN" ? "Anthropic API \u5BC6\u94A5\u5E94\u4EE5 sk-ant- \u5F00\u5934" : "Anthropic API key should start with sk-ant-";
      }
      return true;
    }
  });
  const result = configureOfficialMode(apiKey);
  if (result.success) {
    console.log("");
    console.log(a.green(`\u2714 ${lang === "zh-CN" ? "\u5B98\u65B9 API \u914D\u7F6E\u6210\u529F!" : "Official API configured successfully!"}`));
    console.log("");
  }
  return result;
}
async function runCustomSetup(lang) {
  console.log("");
  console.log(a.green(lang === "zh-CN" ? "\u{1F4CB} \u81EA\u5B9A\u4E49 API \u914D\u7F6E" : "\u{1F4CB} Custom API Configuration"));
  console.log("");
  const { baseUrl } = await inquirer.prompt({
    type: "input",
    name: "baseUrl",
    message: lang === "zh-CN" ? "\u8F93\u5165 API Base URL:" : "Enter API Base URL:",
    validate: (value) => {
      if (!value)
        return lang === "zh-CN" ? "URL \u4E0D\u80FD\u4E3A\u7A7A" : "URL is required";
      if (!value.startsWith("http")) {
        return lang === "zh-CN" ? "URL \u5FC5\u987B\u4EE5 http:// \u6216 https:// \u5F00\u5934" : "URL must start with http:// or https://";
      }
      return true;
    }
  });
  const { apiKey } = await inquirer.prompt({
    type: "password",
    name: "apiKey",
    message: lang === "zh-CN" ? "\u8F93\u5165 API \u5BC6\u94A5:" : "Enter API key:",
    mask: "*",
    validate: (value) => {
      if (!value)
        return lang === "zh-CN" ? "API \u5BC6\u94A5\u4E0D\u80FD\u4E3A\u7A7A" : "API key is required";
      return true;
    }
  });
  const result = configureSimpleMode({
    mode: "simple",
    provider: "custom",
    apiKey,
    baseUrl
  });
  if (result.success) {
    console.log("");
    console.log(a.green(`\u2714 ${lang === "zh-CN" ? "\u81EA\u5B9A\u4E49 API \u914D\u7F6E\u6210\u529F!" : "Custom API configured successfully!"}`));
    console.log("");
  }
  return result;
}
async function runCcrSetup(lang) {
  console.log("");
  console.log(a.green(lang === "zh-CN" ? "\u{1F4CB} CCR \u9AD8\u7EA7\u8DEF\u7531\u914D\u7F6E" : "\u{1F4CB} CCR Advanced Router Configuration"));
  console.log(a.gray(lang === "zh-CN" ? "   CCR \u63D0\u4F9B\u5B8C\u6574\u7684\u6A21\u578B\u8DEF\u7531\u3001\u8F6C\u6362\u548C\u591A\u63D0\u4F9B\u5546\u652F\u6301" : "   CCR provides full model routing, transformation, and multi-provider support"));
  console.log("");
  try {
    const { setupCcrConfiguration } = await import('../chunks/config2.mjs');
    const success = await setupCcrConfiguration();
    return {
      success,
      mode: "ccr",
      provider: "ccr",
      message: success ? lang === "zh-CN" ? "CCR \u914D\u7F6E\u6210\u529F" : "CCR configured successfully" : lang === "zh-CN" ? "CCR \u914D\u7F6E\u5931\u8D25" : "CCR configuration failed"
    };
  } catch (error) {
    return {
      success: false,
      mode: "ccr",
      error: error instanceof Error ? error.message : String(error)
    };
  }
}
async function testApiConnection(lang) {
  lang = resolveApiRouterLang(lang);
  const config = getCurrentConfig();
  if (!config || !config.ANTHROPIC_API_KEY && !config.ANTHROPIC_AUTH_TOKEN) {
    console.log(a.yellow(lang === "zh-CN" ? "\u26A0 \u672A\u914D\u7F6E API" : "\u26A0 No API configured"));
    return false;
  }
  console.log(a.green(lang === "zh-CN" ? "\u{1F50D} \u6D4B\u8BD5 API \u8FDE\u63A5..." : "\u{1F50D} Testing API connection..."));
  try {
    const baseUrl = config.ANTHROPIC_BASE_URL || "https://api.anthropic.com";
    const testUrl = baseUrl.includes("v1") ? baseUrl : `${baseUrl}/v1/models`;
    const response = await fetch(testUrl, {
      method: "GET",
      headers: {
        "x-api-key": config.ANTHROPIC_API_KEY || "",
        "anthropic-version": "2023-06-01"
      }
    });
    if (response.ok || response.status === 401) {
      console.log(a.green(lang === "zh-CN" ? "\u2714 API \u8FDE\u63A5\u6210\u529F" : "\u2714 API connection successful"));
      return true;
    } else {
      console.log(a.yellow(`\u26A0 API returned status: ${response.status}`));
      return false;
    }
  } catch (error) {
    console.log(a.red(lang === "zh-CN" ? "\u2716 API \u8FDE\u63A5\u5931\u8D25" : "\u2716 API connection failed"));
    console.log(a.gray(`  ${error instanceof Error ? error.message : String(error)}`));
    return false;
  }
}

export { configureSimpleMode as a, configureWithPreset as b, configureOfficialMode as c, displayCurrentStatus as d, detectCurrentMode as e, getCurrentConfig as g, quickSetup as q, runConfigWizard as r, testApiConnection as t, validateApiKey as v };
