import a from './index5.mjs';
import { i as inquirer } from './index6.mjs';
import ora from './index8.mjs';
import { CLOUD_ENDPOINTS, getCodeToolRuntimeCommand, isCodeToolType, resolveCodeToolType } from './constants.mjs';
import { c as createApiClient } from '../shared/ccjk.D6ycHbak.mjs';
import { readZcfConfig } from './ccjk-config.mjs';
import { c as setMyclaudeProviderProfiles } from './clavue-config.mjs';
import { r as resolveClaudeFamilyModelSlots } from '../shared/ccjk.B2U7DsPy.mjs';
import { r as resolveClaudeFamilySettingsTarget, n as normalizeClaudeFamilySettings } from '../shared/ccjk.DDL-4C-k.mjs';
import { c as switchToProvider } from './codex.mjs';
import { addProviderToExisting } from './codex-provider-manager.mjs';
import { f as configureApi, o as overwriteModelSettings } from './config.mjs';
import { readJsonConfig, writeJsonConfig } from './json-config.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 '../shared/ccjk.DeWpAShp.mjs';
import './index2.mjs';
import 'node:fs';
import 'node:url';
import '../shared/ccjk.bQ7Dh1g4.mjs';
import '../shared/ccjk.BBtCGd_g.mjs';
import './index3.mjs';
import './fs-operations.mjs';
import 'node:fs/promises';
import '../shared/ccjk.RyizuzOI.mjs';
import '../shared/ccjk.CxpGa6MC.mjs';
import './main.mjs';
import 'module';
import 'node:child_process';
import 'node:stream';
import './platform.mjs';
import '../shared/ccjk.BFQ7yr5S.mjs';
import './prompts.mjs';
import '../shared/ccjk.gDEDGD_t.mjs';
import '../shared/ccjk.DZ2LLOa-.mjs';
import './claude-config.mjs';

const CLOUD_API_BASE_URL = `${CLOUD_ENDPOINTS.MAIN.BASE_URL}${CLOUD_ENDPOINTS.MAIN.API_VERSION}`;
const REQUEST_TIMEOUT = 1e4;
const BUILTIN_PROVIDERS = {
  302: {
    shortcode: "302",
    name: "302.AI",
    apiUrl: "https://api.302.ai",
    description: "302.AI \u4E2D\u8F6C\u670D\u52A1 - \u652F\u6301\u591A\u79CD\u6A21\u578B",
    models: ["gpt-4", "gpt-4-turbo", "gpt-3.5-turbo", "claude-3-opus", "claude-3-sonnet"],
    verified: true,
    category: "relay",
    status: "active",
    createdAt: "2024-01-01T00:00:00Z"
  },
  glm: {
    shortcode: "glm",
    name: "\u667A\u8C31AI",
    apiUrl: "https://open.bigmodel.cn/api/paas/v4",
    description: "\u667A\u8C31 GLM \u5927\u6A21\u578B",
    models: ["glm-4", "glm-4-plus", "glm-3-turbo"],
    verified: true,
    category: "domestic",
    status: "active",
    createdAt: "2024-01-01T00:00:00Z"
  },
  kimi: {
    shortcode: "kimi",
    name: "\u6708\u4E4B\u6697\u9762 Kimi",
    apiUrl: "https://api.moonshot.cn/v1",
    description: "Moonshot Kimi \u5927\u6A21\u578B",
    models: ["moonshot-v1-8k", "moonshot-v1-32k", "moonshot-v1-128k"],
    verified: true,
    category: "domestic",
    status: "active",
    createdAt: "2024-01-01T00:00:00Z"
  },
  minimax: {
    shortcode: "minimax",
    name: "MiniMax",
    apiUrl: "https://api.minimax.chat/v1",
    description: "MiniMax \u5927\u6A21\u578B",
    models: ["abab5.5-chat", "abab6-chat", "abab6.5-chat"],
    verified: true,
    category: "domestic",
    status: "active",
    createdAt: "2024-01-01T00:00:00Z"
  },
  deepseek: {
    shortcode: "deepseek",
    name: "DeepSeek",
    apiUrl: "https://api.deepseek.com/v1",
    description: "DeepSeek \u5927\u6A21\u578B",
    models: ["deepseek-chat", "deepseek-coder"],
    verified: true,
    category: "domestic",
    status: "active",
    createdAt: "2024-01-01T00:00:00Z"
  },
  qwen: {
    shortcode: "qwen",
    name: "\u901A\u4E49\u5343\u95EE",
    apiUrl: "https://dashscope.aliyuncs.com/compatible-mode/v1",
    description: "\u963F\u91CC\u901A\u4E49\u5343\u95EE\u5927\u6A21\u578B",
    models: ["qwen-turbo", "qwen-plus", "qwen-max"],
    verified: true,
    category: "domestic",
    status: "active",
    createdAt: "2024-01-01T00:00:00Z"
  }
};
class ProviderRegistryService {
  client;
  useCloud = true;
  constructor(options) {
    this.client = createApiClient({
      baseUrl: options?.baseUrl || CLOUD_API_BASE_URL,
      timeout: REQUEST_TIMEOUT,
      userAgent: "CCJK-QuickLaunch/1.0"
    });
    this.useCloud = options?.useCloud ?? true;
  }
  // ==========================================================================
  // Query Methods
  // ==========================================================================
  /**
   * Get provider by shortcode
   *
   * First tries cloud registry, falls back to built-in providers.
   *
   * @param shortcode - Provider shortcode (e.g., "302", "glm")
   * @returns Provider info or null if not found
   */
  async getProvider(shortcode) {
    const normalizedCode = shortcode.toLowerCase().trim();
    if (this.useCloud) {
      try {
        const response = await this.client.get(
          `/providers/${encodeURIComponent(normalizedCode)}`
        );
        if (response.success && response.data) {
          return response.data;
        }
      } catch {
      }
    }
    return BUILTIN_PROVIDERS[normalizedCode] || null;
  }
  /**
   * Check if shortcode exists
   *
   * @param shortcode - Provider shortcode to check
   * @returns true if exists, false otherwise
   */
  async exists(shortcode) {
    const provider = await this.getProvider(shortcode);
    return provider !== null;
  }
  /**
   * Check if shortcode is available for registration
   *
   * @param shortcode - Provider shortcode to check
   * @returns true if available, false if taken
   */
  async isAvailable(shortcode) {
    return !await this.exists(shortcode);
  }
  // ==========================================================================
  // Registration Methods
  // ==========================================================================
  /**
   * Create a new provider in the cloud registry
   *
   * @param input - Provider creation data
   * @returns Created provider or error
   */
  async createProvider(input) {
    if (!this.useCloud) {
      return {
        success: false,
        error: {
          code: "CLOUD_DISABLED",
          message: "Cloud service is disabled"
        }
      };
    }
    try {
      const response = await this.client.post(
        "/providers",
        input
      );
      if (response.success && response.data) {
        return {
          success: true,
          data: response.data
        };
      }
      return {
        success: false,
        error: {
          code: response.code || "CREATE_FAILED",
          message: response.error || "Failed to create provider"
        }
      };
    } catch (error) {
      return {
        success: false,
        error: {
          code: "NETWORK_ERROR",
          message: error instanceof Error ? error.message : "Network error"
        }
      };
    }
  }
  // ==========================================================================
  // List Methods
  // ==========================================================================
  /**
   * List all available providers
   *
   * @param options - List options
   * @returns List of providers
   */
  async listProviders(options) {
    if (this.useCloud) {
      try {
        const query = {};
        if (options?.category)
          query.category = options.category;
        if (options?.verified !== void 0)
          query.verified = options.verified;
        if (options?.limit)
          query.limit = options.limit;
        const response = await this.client.get(
          "/providers",
          query
        );
        if (response.success && response.data?.providers) {
          return response.data.providers;
        }
      } catch {
      }
    }
    let providers = Object.values(BUILTIN_PROVIDERS);
    if (options?.category) {
      providers = providers.filter((p) => p.category === options.category);
    }
    if (options?.verified !== void 0) {
      providers = providers.filter((p) => p.verified === options.verified);
    }
    if (options?.limit) {
      providers = providers.slice(0, options.limit);
    }
    return providers;
  }
  /**
   * Get built-in provider (always available, no network)
   *
   * @param shortcode - Provider shortcode
   * @returns Built-in provider or null
   */
  getBuiltinProvider(shortcode) {
    return BUILTIN_PROVIDERS[shortcode.toLowerCase()] || null;
  }
  /**
   * List all built-in providers
   *
   * @returns Array of built-in providers
   */
  listBuiltinProviders() {
    return Object.values(BUILTIN_PROVIDERS);
  }
  // ==========================================================================
  // Configuration
  // ==========================================================================
  /**
   * Enable or disable cloud service
   */
  setUseCloud(enabled) {
    this.useCloud = enabled;
  }
  /**
   * Check if cloud service is enabled
   */
  isCloudEnabled() {
    return this.useCloud;
  }
}
let _instance = null;
function getProviderRegistry() {
  if (!_instance) {
    _instance = new ProviderRegistryService();
  }
  return _instance;
}

function isValidApiUrl(url) {
  try {
    const parsed = new URL(url);
    return parsed.protocol === "https:" || parsed.protocol === "http:";
  } catch {
    return false;
  }
}

const KNOWN_COMMANDS = /* @__PURE__ */ new Set([
  // Core commands
  "",
  "init",
  "update",
  "doctor",
  "help",
  "menu",
  // Quick setup commands (must be before 'quick' deprecated)
  "quick-setup",
  "quick",
  "qs",
  // Extended commands
  "serve",
  "mcp",
  "browser",
  "interview",
  "commit",
  "memory",
  "mem",
  "config",
  "daemon",
  "providers",
  "task",
  "tasks",
  "keybinding",
  "kb",
  "history",
  "hist",
  "ccr",
  "vim",
  "permissions",
  "perm",
  "zero-config",
  "zc",
  "skills",
  "sk",
  "skill",
  "agent",
  "ag",
  "ccu",
  "stats",
  "uninstall",
  "check-updates",
  "check",
  "config-switch",
  "cs",
  "workflows",
  "wf",
  "notification",
  "notify",
  "session",
  "context",
  "ctx",
  "api",
  "team",
  "thinking",
  "think",
  "agent-teams",
  "context-opt",
  "teams",
  "postmortem",
  "pm",
  "claude",
  "monitor",
  "paradigm",
  "trace",
  "status",
  "st",
  "boost",
  "evolution",
  "eval",
  // CCJK v8 commands
  "ccjk:mcp",
  "ccjk-mcp",
  "ccjk:skills",
  "ccjk-skills",
  "ccjk:agents",
  "ccjk-agents",
  "ccjk:hooks",
  "ccjk-hooks",
  "ccjk:all",
  "ccjk-all",
  "ccjk:setup",
  "ccjk-setup",
  // Special commands
  "cloud",
  "system",
  "sys",
  "plugin",
  "completion",
  // Deprecated but still recognized
  "skills-sync",
  "agents-sync",
  "marketplace",
  "deep",
  "setup",
  "sync",
  "versions",
  "upgrade",
  "config-scan",
  "workspace"
]);
function resolveQuickProviderCodeTool(config) {
  if (isCodeToolType(config.codeTool)) {
    return config.codeTool;
  }
  const savedCodeTool = readZcfConfig()?.codeToolType;
  if (isCodeToolType(savedCodeTool)) {
    return savedCodeTool;
  }
  return resolveCodeToolType(config.codeTool);
}
function sanitizeCodexProviderId(input) {
  return input.trim().toLowerCase().replace(/\./g, "-").replace(/\s+/g, "-").replace(/[^a-z0-9\-]/g, "") || "custom";
}
function isKnownCommand(arg) {
  if (!arg)
    return true;
  if (arg.startsWith("-"))
    return true;
  return KNOWN_COMMANDS.has(arg.toLowerCase());
}
function couldBeShortcode(arg) {
  if (!arg)
    return false;
  if (arg.startsWith("-"))
    return false;
  if (isKnownCommand(arg))
    return false;
  return /^[a-z0-9][a-z0-9-]{0,18}[a-z0-9]?$/i.test(arg);
}
async function quickProviderLaunch(shortcode, options = {}) {
  const registry = getProviderRegistry();
  const normalizedCode = shortcode.toLowerCase().trim();
  console.log();
  const spinner = ora({
    text: a.gray(`\u6B63\u5728\u67E5\u8BE2\u4F9B\u5E94\u5546 "${normalizedCode}"...`),
    color: "cyan"
  }).start();
  try {
    const provider = await registry.getProvider(normalizedCode);
    spinner.stop();
    if (provider) {
      return await handleExistingProvider(provider, options);
    } else {
      return await handleNewProvider(normalizedCode, options);
    }
  } catch (error) {
    spinner.fail(a.red("\u67E5\u8BE2\u5931\u8D25"));
    console.error(a.gray(error instanceof Error ? error.message : "\u7F51\u7EDC\u9519\u8BEF"));
    return false;
  }
}
async function handleExistingProvider(provider, options) {
  console.log(a.cyan.bold(`
\u{1F680} \u5FEB\u901F\u914D\u7F6E: ${provider.name}`));
  console.log(a.gray("\u2500".repeat(40)));
  console.log(`   ${a.yellow("\u77ED\u7801:")} ${provider.shortcode}`);
  console.log(`   ${a.yellow("API URL:")} ${provider.apiUrl}`);
  if (provider.description) {
    console.log(`   ${a.yellow("\u63CF\u8FF0:")} ${provider.description}`);
  }
  if (provider.verified) {
    console.log(`   ${a.green("\u2713")} \u5B98\u65B9\u9A8C\u8BC1`);
  }
  console.log();
  const { confirmed } = await inquirer.prompt([
    {
      type: "confirm",
      name: "confirmed",
      message: `\u662F\u5426\u4F7F\u7528 ${a.cyan(provider.name)} \u4F5C\u4E3A API \u4F9B\u5E94\u5546?`,
      default: true
    }
  ]);
  if (!confirmed) {
    console.log(a.gray("\n\u5DF2\u53D6\u6D88\uFF0C\u8FDB\u5165\u4E3B\u83DC\u5355...\n"));
    return false;
  }
  const config = await configureProvider(provider, options);
  if (config) {
    await saveProviderConfig(config);
    showSuccessMessage(config);
    return true;
  }
  return false;
}
async function handleNewProvider(shortcode, options) {
  console.log(a.yellow(`
\u26A0\uFE0F  \u4F9B\u5E94\u5546 "${shortcode}" \u5C1A\u672A\u6CE8\u518C`));
  console.log(a.gray("\u8BE5\u77ED\u7801\u5728\u4E91\u7AEF\u6CE8\u518C\u8868\u4E2D\u4E0D\u5B58\u5728\n"));
  const { createNew } = await inquirer.prompt([
    {
      type: "confirm",
      name: "createNew",
      message: "\u662F\u5426\u521B\u5EFA\u8BE5\u4F9B\u5E94\u5546?",
      default: false
    }
  ]);
  if (!createNew) {
    console.log(a.gray("\n\u5DF2\u53D6\u6D88\uFF0C\u8FDB\u5165\u4E3B\u83DC\u5355...\n"));
    return false;
  }
  const { name, apiUrl } = await inquirer.prompt([
    {
      type: "input",
      name: "name",
      message: "\u4F9B\u5E94\u5546\u540D\u79F0:",
      default: shortcode.toUpperCase(),
      validate: (value) => {
        if (!value.trim())
          return "\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A";
        if (value.length > 50)
          return "\u540D\u79F0\u8FC7\u957F\uFF08\u6700\u591A50\u5B57\u7B26\uFF09";
        return true;
      }
    },
    {
      type: "input",
      name: "apiUrl",
      message: "API URL (\u5982 https://api.example.com/v1):",
      validate: (value) => {
        if (!value.trim())
          return "URL \u4E0D\u80FD\u4E3A\u7A7A";
        if (!isValidApiUrl(value))
          return "\u8BF7\u8F93\u5165\u6709\u6548\u7684 URL\uFF08http:// \u6216 https://\uFF09";
        return true;
      }
    }
  ]);
  const spinner = ora("\u6B63\u5728\u6CE8\u518C\u4F9B\u5E94\u5546...").start();
  try {
    const registry = getProviderRegistry();
    const result = await registry.createProvider({
      shortcode,
      name: name.trim(),
      apiUrl: apiUrl.trim()
    });
    if (result.success && result.data) {
      spinner.succeed(a.green("\u4F9B\u5E94\u5546\u6CE8\u518C\u6210\u529F!"));
      const config = await configureProvider(result.data, options);
      if (config) {
        await saveProviderConfig(config);
        showSuccessMessage(config);
        return true;
      }
    } else {
      spinner.fail(a.red("\u6CE8\u518C\u5931\u8D25"));
      console.error(a.gray(result.error?.message || "\u672A\u77E5\u9519\u8BEF"));
      const { continueLocal } = await inquirer.prompt([
        {
          type: "confirm",
          name: "continueLocal",
          message: "\u662F\u5426\u4ECD\u7136\u4F7F\u7528\u6B64\u914D\u7F6E\uFF08\u4EC5\u672C\u5730\uFF09?",
          default: true
        }
      ]);
      if (continueLocal) {
        const localProvider = {
          shortcode,
          name: name.trim(),
          apiUrl: apiUrl.trim(),
          verified: false,
          createdAt: (/* @__PURE__ */ new Date()).toISOString()
        };
        const config = await configureProvider(localProvider, options);
        if (config) {
          await saveProviderConfig(config);
          showSuccessMessage(config);
          return true;
        }
      }
    }
  } catch (error) {
    spinner.fail(a.red("\u6CE8\u518C\u5931\u8D25"));
    console.error(a.gray(error instanceof Error ? error.message : "\u7F51\u7EDC\u9519\u8BEF"));
  }
  return false;
}
async function configureProvider(provider, _options) {
  console.log(a.cyan("\n\u{1F4DD} \u914D\u7F6E API \u51ED\u8BC1"));
  console.log(a.gray("\u2500".repeat(40)));
  const { apiKey } = await inquirer.prompt([
    {
      type: "password",
      name: "apiKey",
      message: "API Key:",
      mask: "*",
      validate: (value) => {
        if (!value.trim())
          return "API Key \u4E0D\u80FD\u4E3A\u7A7A";
        if (value.length < 10)
          return "API Key \u683C\u5F0F\u4E0D\u6B63\u786E";
        return true;
      }
    }
  ]);
  let model;
  if (provider.models && provider.models.length > 0) {
    const { modelChoice } = await inquirer.prompt([
      {
        type: "list",
        name: "modelChoice",
        message: "\u9009\u62E9\u6A21\u578B:",
        choices: [
          ...provider.models.map((m) => ({
            name: m,
            value: m
          })),
          {
            name: a.gray("\u81EA\u5B9A\u4E49..."),
            value: "__custom__"
          }
        ]
      }
    ]);
    if (modelChoice === "__custom__") {
      const { customModel } = await inquirer.prompt([
        {
          type: "input",
          name: "customModel",
          message: "\u8F93\u5165\u6A21\u578B\u540D\u79F0:",
          validate: (value) => {
            if (!value.trim())
              return "\u6A21\u578B\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A";
            return true;
          }
        }
      ]);
      model = customModel;
    } else {
      model = modelChoice;
    }
  } else {
    const { inputModel } = await inquirer.prompt([
      {
        type: "input",
        name: "inputModel",
        message: "\u6A21\u578B\u540D\u79F0 (\u5982 gpt-4, claude-3-opus):",
        default: "gpt-4",
        validate: (value) => {
          if (!value.trim())
            return "\u6A21\u578B\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A";
          return true;
        }
      }
    ]);
    model = inputModel;
  }
  return {
    shortcode: provider.shortcode,
    provider,
    apiKey: apiKey.trim(),
    model: model.trim(),
    codeTool: _options.codeTool
  };
}
async function saveProviderConfig(config) {
  const spinner = ora("\u6B63\u5728\u4FDD\u5B58\u914D\u7F6E...").start();
  try {
    const codeTool = resolveQuickProviderCodeTool(config);
    if (codeTool === "clavue") {
      const modelSlots = resolveClaudeFamilyModelSlots({ selectedModel: config.model });
      setMyclaudeProviderProfiles([
        {
          id: config.shortcode,
          name: config.provider.name,
          provider: config.shortcode,
          apiKey: config.apiKey,
          baseUrl: config.provider.apiUrl,
          model: modelSlots.primaryModel,
          fastModel: modelSlots.haikuModel,
          authType: "api_key",
          primaryModel: modelSlots.primaryModel,
          defaultHaikuModel: modelSlots.haikuModel,
          defaultSonnetModel: modelSlots.sonnetModel,
          defaultOpusModel: modelSlots.opusModel
        }
      ], config.shortcode);
      spinner.succeed(a.green("\u914D\u7F6E\u5DF2\u4FDD\u5B58"));
      return;
    }
    if (codeTool === "codex") {
      const providerId = sanitizeCodexProviderId(config.shortcode || config.provider.name);
      const tempEnvKey = `${providerId.toUpperCase().replace(/-/g, "_")}_API_KEY`;
      const provider = {
        id: providerId,
        name: config.provider.name,
        baseUrl: config.provider.apiUrl,
        wireApi: "responses",
        tempEnvKey,
        requiresOpenaiAuth: false,
        model: config.model
      };
      const result = await addProviderToExisting(provider, config.apiKey, true);
      if (!result.success) {
        throw new Error(result.error || "Failed to save Codex provider");
      }
      await switchToProvider(providerId);
      spinner.succeed(a.green("\u914D\u7F6E\u5DF2\u4FDD\u5B58"));
      return;
    }
    configureApi({
      url: config.provider.apiUrl,
      key: config.apiKey,
      authType: "api_key"
    }, codeTool);
    const target = resolveClaudeFamilySettingsTarget(codeTool);
    const settings = readJsonConfig(target.settingsFile) || {};
    overwriteModelSettings(settings, { primaryModel: config.model }, "override");
    normalizeClaudeFamilySettings(settings);
    writeJsonConfig(target.settingsFile, settings);
    spinner.succeed(a.green("\u914D\u7F6E\u5DF2\u4FDD\u5B58"));
  } catch (error) {
    spinner.fail(a.red("\u4FDD\u5B58\u5931\u8D25"));
    console.log(a.yellow("\n\u8BF7\u624B\u52A8\u914D\u7F6E:"));
    console.log(a.gray("\u2500".repeat(40)));
    console.log(`${a.cyan("API URL:")} ${config.provider.apiUrl}`);
    console.log(`${a.cyan("Model:")} ${config.model}`);
    console.log(a.gray('\n\u8FD0\u884C "ccjk api" \u8FDB\u884C\u624B\u52A8\u914D\u7F6E'));
    throw error;
  }
}
function showSuccessMessage(config) {
  const codeTool = resolveQuickProviderCodeTool(config);
  const runtimeCommand = getCodeToolRuntimeCommand(codeTool);
  const runtimeName = codeTool === "clavue" ? "Clavue" : codeTool === "codex" ? "Codex" : "Claude Code";
  console.log();
  console.log(a.green.bold("\u2705 \u914D\u7F6E\u5B8C\u6210!"));
  console.log(a.gray("\u2500".repeat(40)));
  console.log(`   ${a.yellow("\u4F9B\u5E94\u5546:")} ${config.provider.name}`);
  console.log(`   ${a.yellow("API URL:")} ${config.provider.apiUrl}`);
  console.log(`   ${a.yellow("\u6A21\u578B:")} ${config.model}`);
  console.log();
  console.log(a.gray(`\u73B0\u5728\u53EF\u4EE5\u5F00\u59CB\u4F7F\u7528 ${runtimeName} \u4E86`));
  console.log(a.gray(`\u8FD0\u884C "${runtimeCommand}" \u542F\u52A8\u5BF9\u8BDD`));
  console.log();
}

export { configureProvider, couldBeShortcode, handleExistingProvider, handleNewProvider, isKnownCommand, quickProviderLaunch, saveProviderConfig };
