import a from '../chunks/index5.mjs';
import { i as inquirer } from '../chunks/index6.mjs';
import { a as getMcpService, d as dynamicMcpRegistry, r as readMcpConfig, b as buildMcpServerConfig, w as writeMcpConfig, M as MCP_SERVICE_CONFIGS } from '../chunks/claude-config.mjs';
import { CLAVUE_CONFIG_FILE, CLAVUE_SETTINGS_FILE, ClAUDE_CONFIG_FILE, CODEX_CONFIG_FILE } from '../chunks/constants.mjs';
import { ensureI18nInitialized, i18n } from '../chunks/index2.mjs';
import { a as readCodexConfig, b as applyCodexPlatformCommand, w as writeCodexConfig } from '../chunks/codex.mjs';
import { exists } from '../chunks/fs-operations.mjs';
import { i as isWindows, g as getSystemRoot } from '../chunks/platform.mjs';
import { r as resolveClaudeFamilySettingsTarget } from './ccjk.DDL-4C-k.mjs';

function detectActiveTool() {
  const hasClavueConfig = exists(CLAVUE_CONFIG_FILE) || exists(CLAVUE_SETTINGS_FILE);
  const hasClaudeConfig = exists(ClAUDE_CONFIG_FILE);
  const hasCodexConfig = exists(CODEX_CONFIG_FILE);
  if (hasClavueConfig) {
    return "clavue";
  }
  if (hasClaudeConfig) {
    return "claude-code";
  }
  if (hasCodexConfig) {
    return "codex";
  }
  return "claude-code";
}
async function installMcpService(serviceId, tool, apiKey) {
  ensureI18nInitialized();
  const service = await getMcpService(serviceId);
  if (!service) {
    return {
      success: false,
      serviceId,
      serviceName: serviceId,
      error: i18n.t("mcp:installer.serviceNotFound", { id: serviceId })
    };
  }
  if (service.requiresApiKey && !apiKey) {
    const promptMessage = service.apiKeyPrompt || i18n.t("mcp:apiKeyPrompt");
    const { inputApiKey } = await inquirer.prompt([{
      type: "input",
      name: "inputApiKey",
      message: promptMessage,
      validate: (input) => !!input || i18n.t("api:keyRequired")
    }]);
    if (!inputApiKey) {
      return {
        success: false,
        serviceId,
        serviceName: service.name,
        error: i18n.t("mcp:installer.apiKeyRequired")
      };
    }
    apiKey = inputApiKey;
  }
  const targetTool = tool || detectActiveTool();
  try {
    if (targetTool === "codex") {
      await installMcpServiceForCodex(serviceId, service.config, apiKey, service.apiKeyEnvVar);
    } else {
      await installMcpServiceForClaudeCode(targetTool, serviceId, service.config, apiKey, service.apiKeyEnvVar);
    }
    dynamicMcpRegistry.addService(serviceId, service.config);
    return {
      success: true,
      serviceId,
      serviceName: service.name
    };
  } catch (error) {
    return {
      success: false,
      serviceId,
      serviceName: service.name,
      error: error instanceof Error ? error.message : String(error)
    };
  }
}
async function installMcpServiceForClaudeCode(tool, serviceId, baseConfig, apiKey, apiKeyEnvVar) {
  let config = readMcpConfig(tool);
  if (!config) {
    config = { mcpServers: {} };
  }
  const serverConfig = buildMcpServerConfig(
    baseConfig,
    apiKey,
    apiKeyEnvVar ? `YOUR_${apiKeyEnvVar}` : "YOUR_API_KEY",
    apiKeyEnvVar
  );
  if (!config.mcpServers) {
    config.mcpServers = {};
  }
  config.mcpServers[serviceId] = serverConfig;
  writeMcpConfig(config, tool);
  await autoAuthorizeMcpService(tool, serviceId);
}
async function installMcpServiceForCodex(serviceId, baseConfig, apiKey, apiKeyEnvVar) {
  const existingConfig = readCodexConfig();
  let command = baseConfig.command || serviceId;
  let args = (baseConfig.args || []).map((arg) => String(arg));
  if (serviceId === "serena") {
    const idx = args.indexOf("--context");
    if (idx >= 0 && idx + 1 < args.length) {
      args[idx + 1] = "codex";
    } else {
      args.push("--context", "codex");
    }
  }
  const serviceConfig = { id: serviceId.toLowerCase(), command, args };
  applyCodexPlatformCommand(serviceConfig);
  command = serviceConfig.command;
  args = serviceConfig.args || [];
  const env = { ...baseConfig.env || {} };
  if (isWindows()) {
    const systemRoot = getSystemRoot();
    if (systemRoot) {
      env.SYSTEMROOT = systemRoot;
    }
  }
  if (apiKey && apiKeyEnvVar) {
    env[apiKeyEnvVar] = apiKey;
  }
  const newService = {
    id: serviceId.toLowerCase(),
    command,
    args,
    env: Object.keys(env).length > 0 ? env : void 0,
    startup_timeout_sec: 30
  };
  const existingServices = existingConfig?.mcpServices || [];
  const mergedMap = /* @__PURE__ */ new Map();
  for (const svc of existingServices) {
    mergedMap.set(svc.id.toLowerCase(), { ...svc });
  }
  mergedMap.set(newService.id, newService);
  const finalServices = Array.from(mergedMap.values());
  const configData = {
    model: existingConfig?.model || null,
    modelProvider: existingConfig?.modelProvider || null,
    providers: existingConfig?.providers || [],
    mcpServices: finalServices,
    features: existingConfig?.features,
    otherConfig: existingConfig?.otherConfig || []
  };
  writeCodexConfig(configData);
}
async function uninstallMcpService(serviceId, tool) {
  ensureI18nInitialized();
  const targetTool = tool || detectActiveTool();
  try {
    if (targetTool === "codex") {
      await uninstallMcpServiceFromCodex(serviceId);
    } else {
      await uninstallMcpServiceFromClaudeCode(targetTool, serviceId);
    }
    dynamicMcpRegistry.removeService(serviceId);
    return {
      success: true,
      serviceId
    };
  } catch (error) {
    return {
      success: false,
      serviceId,
      error: error instanceof Error ? error.message : String(error)
    };
  }
}
async function uninstallMcpServiceFromClaudeCode(tool, serviceId) {
  const config = readMcpConfig(tool);
  if (!config || !config.mcpServers) {
    throw new Error(i18n.t("mcp:installer.noConfig"));
  }
  const normalizedId = serviceId.toLowerCase();
  const existingKey = Object.keys(config.mcpServers).find(
    (key) => key.toLowerCase() === normalizedId
  );
  if (!existingKey) {
    throw new Error(i18n.t("mcp:installer.serviceNotInstalled", { id: serviceId }));
  }
  delete config.mcpServers[existingKey];
  writeMcpConfig(config, tool);
  await removeAuthorizeMcpService(tool, serviceId);
}
async function uninstallMcpServiceFromCodex(serviceId) {
  const existingConfig = readCodexConfig();
  if (!existingConfig || !existingConfig.mcpServices) {
    throw new Error(i18n.t("mcp:installer.noConfig"));
  }
  const normalizedId = serviceId.toLowerCase();
  const serviceIndex = existingConfig.mcpServices.findIndex(
    (svc) => svc.id.toLowerCase() === normalizedId
  );
  if (serviceIndex === -1) {
    throw new Error(i18n.t("mcp:installer.serviceNotInstalled", { id: serviceId }));
  }
  existingConfig.mcpServices.splice(serviceIndex, 1);
  writeCodexConfig(existingConfig);
}
async function listInstalledMcpServices(tool) {
  ensureI18nInitialized();
  const targetTool = tool || detectActiveTool();
  if (targetTool === "codex") {
    return listInstalledMcpServicesFromCodex();
  } else {
    return listInstalledMcpServicesFromClaudeCode(targetTool);
  }
}
function listInstalledMcpServicesFromClaudeCode(tool) {
  const config = readMcpConfig(tool);
  if (!config || !config.mcpServers) {
    return [];
  }
  const services = [];
  for (const [id, serverConfig] of Object.entries(config.mcpServers)) {
    const knownService = MCP_SERVICE_CONFIGS.find(
      (s) => s.id.toLowerCase() === id.toLowerCase()
    );
    services.push({
      id,
      name: knownService?.id || id,
      command: serverConfig.command,
      args: serverConfig.args,
      url: serverConfig.url,
      type: serverConfig.type || "stdio"
    });
  }
  return services;
}
function listInstalledMcpServicesFromCodex() {
  const config = readCodexConfig();
  if (!config || !config.mcpServices) {
    return [];
  }
  const services = [];
  for (const svc of config.mcpServices) {
    const knownService = MCP_SERVICE_CONFIGS.find(
      (s) => s.id.toLowerCase() === svc.id.toLowerCase()
    );
    services.push({
      id: svc.id,
      name: knownService?.id || svc.id,
      command: svc.command,
      args: svc.args,
      type: "stdio"
    });
  }
  return services;
}
async function isMcpServiceInstalled(serviceId, tool) {
  const installedServices = await listInstalledMcpServices(tool);
  const normalizedId = serviceId.toLowerCase();
  return installedServices.some((svc) => svc.id.toLowerCase() === normalizedId);
}
async function installMcpServices(serviceIds, tool) {
  const results = [];
  for (const serviceId of serviceIds) {
    const result = await installMcpService(serviceId, tool);
    results.push(result);
  }
  return results;
}
async function displayInstalledMcpServices(tool) {
  ensureI18nInitialized();
  const targetTool = tool || detectActiveTool();
  const services = await listInstalledMcpServices(targetTool);
  if (services.length === 0) {
    console.log(a.yellow(i18n.t("mcp:installer.noServicesInstalled")));
    return;
  }
  console.log(a.green.bold(`
${i18n.t("mcp:installer.installedServices", { tool: targetTool })}
`));
  services.forEach((service, idx) => {
    console.log(`${a.green(`${idx + 1}.`)} ${a.bold(service.name)} ${a.dim(`[${service.id}]`)}`);
    if (service.command) {
      console.log(`   ${a.dim(`Command: ${service.command}`)}`);
    }
    if (service.url) {
      console.log(`   ${a.dim(`URL: ${service.url}`)}`);
    }
    console.log("");
  });
}
async function autoAuthorizeMcpService(tool, serviceId) {
  const mcpPermission = `mcp__${serviceId.toLowerCase().replace(/-/g, "_")}__*`;
  const target = resolveClaudeFamilySettingsTarget(tool);
  const { readClaudeConfig } = await import('../chunks/claude-config2.mjs');
  const { updateClaudeConfig } = await import('../chunks/claude-config2.mjs');
  const currentSettings = readClaudeConfig(target.settingsFile) || {};
  if (!currentSettings.permissions) {
    currentSettings.permissions = {};
  }
  if (!currentSettings.permissions.allow) {
    currentSettings.permissions.allow = [];
  }
  if (!currentSettings.permissions.allow.includes(mcpPermission)) {
    currentSettings.permissions.allow.push(mcpPermission);
    updateClaudeConfig({
      permissions: currentSettings.permissions
    }, {}, target.settingsFile);
  }
}
async function removeAuthorizeMcpService(tool, serviceId) {
  const mcpPermission = `mcp__${serviceId.toLowerCase().replace(/-/g, "_")}__*`;
  const target = resolveClaudeFamilySettingsTarget(tool);
  const { readClaudeConfig } = await import('../chunks/claude-config2.mjs');
  const { updateClaudeConfig } = await import('../chunks/claude-config2.mjs');
  const currentSettings = readClaudeConfig(target.settingsFile) || {};
  if (currentSettings.permissions?.allow) {
    const index = currentSettings.permissions.allow.indexOf(mcpPermission);
    if (index !== -1) {
      currentSettings.permissions.allow.splice(index, 1);
      updateClaudeConfig({
        permissions: currentSettings.permissions
      }, {}, target.settingsFile);
    }
  }
}

export { installMcpServices as a, isMcpServiceInstalled as b, displayInstalledMcpServices as d, installMcpService as i, uninstallMcpService as u };
