import { execSync } from 'node:child_process';
import process__default from 'node:process';
import { ensureI18nInitialized, i18n } from './index2.mjs';
import { CLAUDE_VSC_CONFIG_FILE } from './constants.mjs';
import { r as resolveClaudeFamilySettingsTarget, a as applyTrustedOperatorPermissions, n as normalizeClaudeFamilySettings } from '../shared/ccjk.DDL-4C-k.mjs';
import { readJsonConfig, writeJsonConfig, backupJsonConfig } from './json-config.mjs';
import { i as isWindows, m as getMcpCommand } from './platform.mjs';
import { j as join } from '../shared/ccjk.bQ7Dh1g4.mjs';

const MCP_SERVICE_CONFIGS = [
  // Documentation and research services
  {
    id: "context7",
    requiresApiKey: false,
    defaultSelected: true,
    config: {
      type: "stdio",
      command: "npx",
      args: ["-y", "@upstash/context7-mcp@latest"],
      env: {}
    }
  },
  {
    id: "open-websearch",
    requiresApiKey: false,
    config: {
      type: "stdio",
      command: "npx",
      args: ["-y", "open-websearch@latest"],
      env: {
        MODE: "stdio",
        DEFAULT_SEARCH_ENGINE: "duckduckgo",
        ALLOWED_SEARCH_ENGINES: "duckduckgo,bing,brave"
      }
    }
  },
  {
    id: "mcp-deepwiki",
    requiresApiKey: false,
    config: {
      type: "stdio",
      command: "npx",
      args: ["-y", "mcp-deepwiki@latest"],
      env: {}
    }
  },
  {
    id: "spec-workflow",
    requiresApiKey: false,
    config: {
      type: "stdio",
      command: "npx",
      args: ["-y", "@pimzino/spec-workflow-mcp@latest"],
      env: {}
    }
  },
  {
    id: "serena",
    requiresApiKey: false,
    config: {
      type: "stdio",
      command: "uvx",
      args: ["--from", "git+https://github.com/oraios/serena", "serena", "start-mcp-server", "--context", "ide-assistant", "--enable-web-dashboard", "false"],
      env: {}
    },
    platformRequirements: {
      requiredCommands: ["uvx"]
    }
  },
  {
    id: "Playwright",
    requiresApiKey: false,
    config: {
      type: "stdio",
      command: "npx",
      args: ["-y", "@playwright/mcp@latest", "--browser", "chromium"],
      env: {}
    },
    platformRequirements: {
      platforms: ["macos", "windows"],
      requiresGui: true
    }
  },
  {
    id: "intent-engine",
    requiresApiKey: false,
    config: {
      type: "stdio",
      command: "npx",
      args: ["-y", "@origintask/intent-engine@latest", "mcp"],
      env: {}
    }
  },
  {
    id: "sqlite",
    requiresApiKey: false,
    config: {
      type: "stdio",
      command: "npx",
      args: ["-y", "@anthropic-ai/mcp-server-sqlite@latest"],
      env: {}
    }
  }
];
async function getMcpServices() {
  ensureI18nInitialized();
  const mcpServiceList = [
    {
      id: "context7",
      name: i18n.t("mcp:services.context7.name"),
      description: i18n.t("mcp:services.context7.description")
    },
    {
      id: "open-websearch",
      name: i18n.t("mcp:services.open-websearch.name"),
      description: i18n.t("mcp:services.open-websearch.description")
    },
    {
      id: "mcp-deepwiki",
      name: i18n.t("mcp:services.mcp-deepwiki.name"),
      description: i18n.t("mcp:services.mcp-deepwiki.description")
    },
    {
      id: "spec-workflow",
      name: i18n.t("mcp:services.spec-workflow.name"),
      description: i18n.t("mcp:services.spec-workflow.description")
    },
    {
      id: "serena",
      name: i18n.t("mcp:services.serena.name"),
      description: i18n.t("mcp:services.serena.description")
    },
    {
      id: "Playwright",
      name: i18n.t("mcp:services.Playwright.name"),
      description: i18n.t("mcp:services.Playwright.description")
    },
    {
      id: "intent-engine",
      name: i18n.t("mcp:services.intent-engine.name"),
      description: i18n.t("mcp:services.intent-engine.description")
    },
    {
      id: "sqlite",
      name: i18n.t("mcp:services.sqlite.name"),
      description: i18n.t("mcp:services.sqlite.description")
    }
  ];
  return MCP_SERVICE_CONFIGS.map((config) => {
    const serviceInfo = mcpServiceList.find((s) => s.id === config.id);
    const service = {
      id: config.id,
      name: serviceInfo?.name || config.id,
      description: serviceInfo?.description || "",
      requiresApiKey: config.requiresApiKey,
      config: config.config
    };
    if (config.apiKeyEnvVar) {
      service.apiKeyEnvVar = config.apiKeyEnvVar;
    }
    return service;
  });
}
async function getMcpService(id) {
  const services = await getMcpServices();
  return services.find((service) => service.id === id);
}
function detectPlatform() {
  const platform = process__default.platform;
  const env = process__default.env;
  const isWsl = !!(env.WSL_DISTRO_NAME || env.WSLENV || env.PATH && env.PATH.includes("/mnt/c/"));
  const isTermux = !!(env.TERMUX_VERSION || env.PREFIX?.includes("com.termux"));
  const isHeadless = !!(env.SSH_CLIENT || env.SSH_TTY || env.SSH_CONNECTION || !env.DISPLAY && platform === "linux");
  const hasGui = (() => {
    if (platform === "darwin")
      return true;
    if (platform === "win32")
      return !isHeadless;
    if (isWsl || isTermux)
      return false;
    if (platform === "linux")
      return !!env.DISPLAY || !!env.WAYLAND_DISPLAY;
    return false;
  })();
  let detectedPlatform;
  if (platform === "darwin") {
    detectedPlatform = "macos";
  } else if (platform === "win32") {
    detectedPlatform = "windows";
  } else if (isWsl) {
    detectedPlatform = "wsl";
  } else if (isTermux) {
    detectedPlatform = "termux";
  } else if (platform === "linux") {
    detectedPlatform = "linux";
  } else {
    detectedPlatform = "unknown";
  }
  return {
    platform: detectedPlatform,
    hasGui,
    isHeadless
  };
}
function isCommandAvailable(command) {
  try {
    execSync(`which ${command}`, { stdio: "ignore" });
    return true;
  } catch {
    return false;
  }
}
function isMcpServiceCompatible(serviceId) {
  const config = MCP_SERVICE_CONFIGS.find((c) => c.id === serviceId);
  if (!config) {
    return { compatible: false, reason: "Service not found" };
  }
  const requirements = config.platformRequirements;
  if (!requirements) {
    return { compatible: true };
  }
  const { platform, hasGui } = detectPlatform();
  if (requirements.platforms && requirements.platforms.length > 0) {
    if (platform !== "unknown" && !requirements.platforms.includes(platform)) {
      return {
        compatible: false,
        reason: `Not supported on ${platform}. Requires: ${requirements.platforms.join(", ")}`
      };
    }
  }
  if (requirements.requiresGui && !hasGui) {
    return {
      compatible: false,
      reason: "Requires GUI environment (X11/Wayland/Desktop)"
    };
  }
  if (requirements.requiredCommands) {
    for (const cmd of requirements.requiredCommands) {
      if (!isCommandAvailable(cmd)) {
        return {
          compatible: false,
          reason: `Required command not found: ${cmd}`
        };
      }
    }
  }
  return { compatible: true };
}
async function getMcpServicesWithCompatibility() {
  const allServices = await getMcpServices();
  return allServices.map((service) => {
    const { compatible, reason } = isMcpServiceCompatible(service.id);
    return {
      ...service,
      compatible,
      incompatibleReason: reason
    };
  });
}
const DEFAULT_MCP_TOOL_SEARCH_CONFIG = {
  mcpAutoEnableThreshold: 10,
  excludedServices: ["mcp-search", "context7"]
};
function getMcpToolSearchConfig() {
  const env = process__default.env;
  return {
    mcpAutoEnableThreshold: env.MCP_AUTO_THRESHOLD || DEFAULT_MCP_TOOL_SEARCH_CONFIG.mcpAutoEnableThreshold,
    dynamicServiceDiscovery: env.MCP_DYNAMIC_DISCOVERY !== "false",
    listChangedNotifications: env.MCP_LIST_CHANGED !== "false",
    excludedServices: env.MCP_EXCLUDED_SERVICES?.split(",").map((s) => s.trim()).filter(Boolean) || DEFAULT_MCP_TOOL_SEARCH_CONFIG.excludedServices
  };
}
class DynamicMcpServiceRegistry {
  _services = /* @__PURE__ */ new Map();
  _listeners = /* @__PURE__ */ new Set();
  _enabled = false;
  /**
   * Enable dynamic service discovery
   */
  enable() {
    this._enabled = true;
  }
  /**
   * Disable dynamic service discovery
   */
  disable() {
    this._enabled = false;
  }
  /**
   * Check if dynamic discovery is enabled
   */
  isEnabled() {
    return this._enabled;
  }
  /**
   * Add a service dynamically
   */
  addService(serviceId, config) {
    if (!this._enabled) {
      return false;
    }
    const isUpdate = this._services.has(serviceId);
    this._services.set(serviceId, config);
    this._notify({
      type: isUpdate ? "updated" : "added",
      serviceId,
      timestamp: Date.now(),
      config
    });
    return true;
  }
  /**
   * Remove a service dynamically
   */
  removeService(serviceId) {
    if (!this._enabled || !this._services.has(serviceId)) {
      return false;
    }
    const config = this._services.get(serviceId);
    this._services.delete(serviceId);
    this._notify({
      type: "removed",
      serviceId,
      timestamp: Date.now(),
      config
    });
    return true;
  }
  /**
   * Get a service configuration
   */
  getService(serviceId) {
    return this._services.get(serviceId);
  }
  /**
   * List all dynamically registered services
   */
  listServices() {
    return new Map(this._services);
  }
  /**
   * Subscribe to list change notifications
   */
  subscribe(listener) {
    this._listeners.add(listener);
    return () => this._listeners.delete(listener);
  }
  /**
   * Notify all listeners of a change
   */
  _notify(notification) {
    const toolSearchConfig = getMcpToolSearchConfig();
    if (toolSearchConfig.listChangedNotifications) {
      for (const listener of Array.from(this._listeners)) {
        try {
          listener(notification);
        } catch (error) {
          console.error("Error notifying MCP list change listener:", error);
        }
      }
    }
  }
}
const dynamicMcpRegistry = new DynamicMcpServiceRegistry();

function mergeArraysUnique(arr1, arr2) {
  const combined = [...arr1 || [], ...arr2 || []];
  return [...new Set(combined)];
}
function isPlainObject(value) {
  return value !== null && typeof value === "object" && value.constructor === Object && Object.prototype.toString.call(value) === "[object Object]";
}
function deepMerge(target, source, options = {}) {
  const { mergeArrays = false, arrayMergeStrategy = "replace" } = options;
  const result = { ...target };
  for (const key in source) {
    const sourceValue = source[key];
    const targetValue = result[key];
    if (sourceValue === void 0) {
      continue;
    }
    if (isPlainObject(sourceValue) && isPlainObject(targetValue)) {
      result[key] = deepMerge(targetValue, sourceValue, options);
    } else if (Array.isArray(sourceValue)) {
      if (!mergeArrays || !Array.isArray(targetValue)) {
        result[key] = sourceValue;
      } else {
        switch (arrayMergeStrategy) {
          case "concat":
            result[key] = [...targetValue, ...sourceValue];
            break;
          case "unique":
            result[key] = mergeArraysUnique(targetValue, sourceValue);
            break;
          case "replace":
          default:
            result[key] = sourceValue;
            break;
        }
      }
    } else {
      result[key] = sourceValue;
    }
  }
  return result;
}
function deepClone(obj) {
  if (obj === null || typeof obj !== "object") {
    return obj;
  }
  if (obj instanceof Date) {
    return new Date(obj.getTime());
  }
  if (Array.isArray(obj)) {
    return obj.map((item) => deepClone(item));
  }
  if (isPlainObject(obj)) {
    const cloned = {};
    for (const key in obj) {
      cloned[key] = deepClone(obj[key]);
    }
    return cloned;
  }
  return obj;
}

function readMcpConfig(codeTool) {
  return readJsonConfig(resolveClaudeFamilySettingsTarget(codeTool).runtimeConfigFile);
}
function writeMcpConfig(config, codeTool) {
  writeJsonConfig(resolveClaudeFamilySettingsTarget(codeTool).runtimeConfigFile, config);
}
function backupMcpConfig(codeTool) {
  const target = resolveClaudeFamilySettingsTarget(codeTool);
  const backupBaseDir = join(target.configDir, target.runtimeBackupDirName);
  return backupJsonConfig(target.runtimeConfigFile, backupBaseDir);
}
function mergeMcpServers(existing, newServers) {
  const config = existing || { mcpServers: {} };
  if (!config.mcpServers) {
    config.mcpServers = {};
  }
  Object.assign(config.mcpServers, newServers);
  return config;
}
function replaceMcpServers(existing, newServers) {
  const config = existing ? { ...existing } : { mcpServers: {} };
  config.mcpServers = { ...newServers };
  return config;
}
function applyPlatformCommand(config) {
  if (isWindows() && config.command) {
    const mcpCmd = getMcpCommand(config.command);
    if (mcpCmd[0] === "cmd") {
      config.command = mcpCmd[0];
      config.args = [...mcpCmd.slice(1), ...config.args || []];
    }
  }
}
function buildMcpServerConfig(baseConfig, apiKey, placeholder = "YOUR_EXA_API_KEY", envVarName) {
  const config = deepClone(baseConfig);
  applyPlatformCommand(config);
  if (!apiKey) {
    return config;
  }
  if (envVarName && config.env) {
    config.env[envVarName] = apiKey;
    return config;
  }
  if (config.args) {
    config.args = config.args.map((arg) => arg.replace(placeholder, apiKey));
  }
  if (config.url) {
    config.url = config.url.replace(placeholder, apiKey);
  }
  return config;
}
function fixWindowsMcpConfig(config) {
  if (!isWindows() || !config.mcpServers) {
    return config;
  }
  const fixed = { ...config };
  for (const [, serverConfig] of Object.entries(fixed.mcpServers)) {
    if (serverConfig && typeof serverConfig === "object" && "command" in serverConfig) {
      applyPlatformCommand(serverConfig);
    }
  }
  return fixed;
}
function addCompletedOnboarding(codeTool) {
  try {
    let config = readMcpConfig(codeTool);
    if (!config) {
      config = { mcpServers: {} };
    }
    if (config.hasCompletedOnboarding === true) {
      return;
    }
    config.hasCompletedOnboarding = true;
    writeMcpConfig(config, codeTool);
  } catch (error) {
    console.error("Failed to add onboarding flag", error);
    throw error;
  }
}
function ensureApiKeyApproved(config, apiKey) {
  if (!apiKey || typeof apiKey !== "string" || apiKey.trim() === "") {
    return config;
  }
  const truncatedApiKey = apiKey.substring(0, 20);
  const updatedConfig = { ...config };
  if (!updatedConfig.customApiKeyResponses) {
    updatedConfig.customApiKeyResponses = {
      approved: [],
      rejected: []
    };
  }
  if (!Array.isArray(updatedConfig.customApiKeyResponses.approved)) {
    updatedConfig.customApiKeyResponses.approved = [];
  }
  if (!Array.isArray(updatedConfig.customApiKeyResponses.rejected)) {
    updatedConfig.customApiKeyResponses.rejected = [];
  }
  const rejectedIndex = updatedConfig.customApiKeyResponses.rejected.indexOf(truncatedApiKey);
  if (rejectedIndex > -1) {
    updatedConfig.customApiKeyResponses.rejected.splice(rejectedIndex, 1);
  }
  if (!updatedConfig.customApiKeyResponses.approved.includes(truncatedApiKey)) {
    updatedConfig.customApiKeyResponses.approved.push(truncatedApiKey);
  }
  return updatedConfig;
}
function manageApiKeyApproval(apiKey, codeTool) {
  try {
    let config = readMcpConfig(codeTool);
    if (!config) {
      config = { mcpServers: {} };
    }
    const updatedConfig = ensureApiKeyApproved(config, apiKey);
    writeMcpConfig(updatedConfig, codeTool);
  } catch (error) {
    ensureI18nInitialized();
    console.error(i18n.t("mcp:apiKeyApprovalFailed"), error);
  }
}
function setPrimaryApiKey(codeTool) {
  try {
    if (resolveClaudeFamilySettingsTarget(codeTool).codeTool !== "claude-code") {
      return;
    }
    let config = readJsonConfig(CLAUDE_VSC_CONFIG_FILE);
    if (!config) {
      config = {};
    }
    config.primaryApiKey = "ccjk";
    writeJsonConfig(CLAUDE_VSC_CONFIG_FILE, config);
  } catch (error) {
    ensureI18nInitialized();
    console.error(i18n.t("mcp:primaryApiKeySetFailed"), error);
  }
}
function getKnownMcpServiceIds() {
  return new Set(MCP_SERVICE_CONFIGS.map((service) => service.id));
}
function getMcpPermission(serviceId) {
  return `mcp__${serviceId.toLowerCase().replace(/-/g, "_")}__*`;
}
function syncMcpPermissions(codeTool) {
  const target = resolveClaudeFamilySettingsTarget(codeTool);
  const mcpConfig = readMcpConfig(target.codeTool);
  const knownServiceIds = getKnownMcpServiceIds();
  const managedMcpServerIds = Object.keys(mcpConfig?.mcpServers || {}).filter((id) => knownServiceIds.has(id));
  const settingsPath = target.settingsFile;
  const settings = readJsonConfig(settingsPath) || {};
  const allow = Array.isArray(settings.permissions?.allow) ? settings.permissions.allow.filter((permission) => typeof permission === "string") : [];
  const managedMcpPermissions = new Set(
    [...knownServiceIds].map(getMcpPermission)
  );
  const nonManagedPerms = allow.filter((permission) => !managedMcpPermissions.has(permission));
  const mcpPerms = managedMcpServerIds.map(getMcpPermission);
  settings.permissions = {
    ...settings.permissions || {},
    allow: [...nonManagedPerms, ...mcpPerms]
  };
  applyTrustedOperatorPermissions(settings);
  normalizeClaudeFamilySettings(settings);
  writeJsonConfig(settingsPath, settings);
}

const claudeConfig = {
  __proto__: null,
  addCompletedOnboarding: addCompletedOnboarding,
  backupMcpConfig: backupMcpConfig,
  buildMcpServerConfig: buildMcpServerConfig,
  ensureApiKeyApproved: ensureApiKeyApproved,
  fixWindowsMcpConfig: fixWindowsMcpConfig,
  manageApiKeyApproval: manageApiKeyApproval,
  mergeMcpServers: mergeMcpServers,
  readMcpConfig: readMcpConfig,
  replaceMcpServers: replaceMcpServers,
  setPrimaryApiKey: setPrimaryApiKey,
  syncMcpPermissions: syncMcpPermissions,
  writeMcpConfig: writeMcpConfig
};

export { MCP_SERVICE_CONFIGS as M, getMcpService as a, buildMcpServerConfig as b, backupMcpConfig as c, dynamicMcpRegistry as d, deepMerge as e, fixWindowsMcpConfig as f, getMcpServices as g, setPrimaryApiKey as h, addCompletedOnboarding as i, isMcpServiceCompatible as j, getMcpServicesWithCompatibility as k, replaceMcpServers as l, mergeMcpServers as m, claudeConfig as n, readMcpConfig as r, syncMcpPermissions as s, writeMcpConfig as w };
