import { join } from 'node:path';
import { cwd } from 'node:process';
import a from './index5.mjs';
import { c as consola, a as analyzeProject, g as getTemplatesClient } from '../shared/ccjk.CoCHVXl3.mjs';
import { i as inquirer } from './index6.mjs';
import { CLAUDE_DIR } from './constants.mjs';
import { ensureI18nInitialized, i18n } from './index2.mjs';
import { c as backupMcpConfig, r as readMcpConfig, m as mergeMcpServers, w as writeMcpConfig } from './claude-config.mjs';
import { c as commandExists } from './platform.mjs';
import '../shared/ccjk.BAGoDD49.mjs';
import 'node:fs';
import './index10.mjs';
import '../shared/ccjk.bQ7Dh1g4.mjs';
import 'tinyglobby';
import '../shared/ccjk.BBtCGd_g.mjs';
import 'node:readline';
import 'stream';
import 'node:tty';
import 'node:async_hooks';
import '../shared/ccjk.Cjgrln_h.mjs';
import 'node:util';
import 'tty';
import 'fs';
import 'child_process';
import 'node:os';
import 'node:crypto';
import 'buffer';
import 'string_decoder';
import 'node:url';
import 'node:child_process';
import '../shared/ccjk.DDL-4C-k.mjs';
import './ccjk-config.mjs';
import './index3.mjs';
import './fs-operations.mjs';
import 'node:fs/promises';
import './json-config.mjs';
import '../shared/ccjk.RyizuzOI.mjs';
import './main.mjs';
import 'module';
import 'node:stream';

const mcpServiceTemplates = {
  // ============================================================================
  // Language Server Integrations
  // ============================================================================
  "typescript-language-server": {
    id: "typescript-language-server",
    name: {
      "en": "TypeScript Language Server",
      "zh-CN": "TypeScript \u8BED\u8A00\u670D\u52A1\u5668"
    },
    description: {
      "en": "Provides TypeScript/JavaScript language support with IntelliSense, error checking, and refactoring",
      "zh-CN": "\u63D0\u4F9B TypeScript/JavaScript \u8BED\u8A00\u652F\u6301\uFF0C\u5305\u62EC\u667A\u80FD\u611F\u77E5\u3001\u9519\u8BEF\u68C0\u67E5\u548C\u91CD\u6784\u529F\u80FD"
    },
    type: "stdio",
    command: "typescript-language-server",
    args: ["--stdio"],
    env: {},
    requiredFor: ["typescript", "javascript", "react", "vue", "angular", "nextjs"],
    optionalFor: ["nodejs", "web"],
    installCheck: "typescript-language-server --version",
    installCommand: "npm install -g typescript-language-server typescript",
    category: "language",
    platforms: ["windows", "macos", "linux", "wsl"],
    requiredCommands: ["node", "npm"]
  },
  "python-lsp-server": {
    id: "python-lsp-server",
    name: {
      "en": "Python LSP Server",
      "zh-CN": "Python LSP \u670D\u52A1\u5668"
    },
    description: {
      "en": "Python Language Server Protocol implementation with linting, formatting, and code completion",
      "zh-CN": "Python \u8BED\u8A00\u670D\u52A1\u5668\u534F\u8BAE\u5B9E\u73B0\uFF0C\u63D0\u4F9B\u4EE3\u7801\u68C0\u67E5\u3001\u683C\u5F0F\u5316\u548C\u81EA\u52A8\u8865\u5168\u529F\u80FD"
    },
    type: "stdio",
    command: "pylsp",
    args: [],
    env: {},
    requiredFor: ["python", "django", "flask", "fastapi"],
    optionalFor: ["data-science", "machine-learning"],
    installCheck: "pylsp --version",
    installCommand: "pip install python-lsp-server[all]",
    category: "language",
    platforms: ["windows", "macos", "linux", "wsl"],
    requiredCommands: ["python", "pip"]
  },
  "gopls": {
    id: "gopls",
    name: {
      "en": "Go Language Server",
      "zh-CN": "Go \u8BED\u8A00\u670D\u52A1\u5668"
    },
    description: {
      "en": "Official Go language server providing code intelligence, navigation, and refactoring",
      "zh-CN": "\u5B98\u65B9 Go \u8BED\u8A00\u670D\u52A1\u5668\uFF0C\u63D0\u4F9B\u4EE3\u7801\u667A\u80FD\u3001\u5BFC\u822A\u548C\u91CD\u6784\u529F\u80FD"
    },
    type: "stdio",
    command: "gopls",
    args: [],
    env: {},
    requiredFor: ["go", "golang"],
    optionalFor: ["microservices", "backend"],
    installCheck: "gopls version",
    installCommand: "go install golang.org/x/tools/gopls@latest",
    category: "language",
    platforms: ["windows", "macos", "linux", "wsl"],
    requiredCommands: ["go"]
  },
  "rust-analyzer": {
    id: "rust-analyzer",
    name: {
      "en": "Rust Analyzer",
      "zh-CN": "Rust \u5206\u6790\u5668"
    },
    description: {
      "en": "Fast and feature-rich language server for Rust with real-time diagnostics and code assistance",
      "zh-CN": "\u5FEB\u901F\u4E14\u529F\u80FD\u4E30\u5BCC\u7684 Rust \u8BED\u8A00\u670D\u52A1\u5668\uFF0C\u63D0\u4F9B\u5B9E\u65F6\u8BCA\u65AD\u548C\u4EE3\u7801\u8F85\u52A9"
    },
    type: "stdio",
    command: "rust-analyzer",
    args: [],
    env: {},
    requiredFor: ["rust", "cargo"],
    optionalFor: ["systems-programming", "webassembly"],
    installCheck: "rust-analyzer --version",
    installCommand: "rustup component add rust-analyzer",
    category: "language",
    platforms: ["windows", "macos", "linux", "wsl"],
    requiredCommands: ["rustup", "cargo"]
  },
  // ============================================================================
  // Development Tooling
  // ============================================================================
  "eslint-mcp": {
    id: "eslint-mcp",
    name: {
      "en": "ESLint MCP Server",
      "zh-CN": "ESLint MCP \u670D\u52A1\u5668"
    },
    description: {
      "en": "JavaScript/TypeScript linting and code quality analysis through MCP protocol",
      "zh-CN": "\u901A\u8FC7 MCP \u534F\u8BAE\u63D0\u4F9B JavaScript/TypeScript \u4EE3\u7801\u68C0\u67E5\u548C\u8D28\u91CF\u5206\u6790"
    },
    type: "stdio",
    command: "npx",
    args: ["-y", "@modelcontextprotocol/server-eslint@latest"],
    env: {},
    requiredFor: [],
    optionalFor: ["javascript", "typescript", "react", "vue", "angular", "nodejs"],
    installCheck: "npx @modelcontextprotocol/server-eslint@latest --version",
    installCommand: "npm install -g @modelcontextprotocol/server-eslint",
    category: "tooling",
    platforms: ["windows", "macos", "linux", "wsl"],
    requiredCommands: ["node", "npm"]
  },
  "prettier-mcp": {
    id: "prettier-mcp",
    name: {
      "en": "Prettier MCP Server",
      "zh-CN": "Prettier MCP \u670D\u52A1\u5668"
    },
    description: {
      "en": "Code formatting service for multiple languages through MCP protocol",
      "zh-CN": "\u901A\u8FC7 MCP \u534F\u8BAE\u4E3A\u591A\u79CD\u8BED\u8A00\u63D0\u4F9B\u4EE3\u7801\u683C\u5F0F\u5316\u670D\u52A1"
    },
    type: "stdio",
    command: "npx",
    args: ["-y", "@modelcontextprotocol/server-prettier@latest"],
    env: {},
    requiredFor: [],
    optionalFor: ["javascript", "typescript", "html", "css", "json", "markdown", "yaml"],
    installCheck: "npx @modelcontextprotocol/server-prettier@latest --version",
    installCommand: "npm install -g @modelcontextprotocol/server-prettier",
    category: "tooling",
    platforms: ["windows", "macos", "linux", "wsl"],
    requiredCommands: ["node", "npm"]
  },
  // ============================================================================
  // Git Integration
  // ============================================================================
  "git-mcp": {
    id: "git-mcp",
    name: {
      "en": "Git MCP Server",
      "zh-CN": "Git MCP \u670D\u52A1\u5668"
    },
    description: {
      "en": "Git repository operations and version control through MCP protocol",
      "zh-CN": "\u901A\u8FC7 MCP \u534F\u8BAE\u63D0\u4F9B Git \u4ED3\u5E93\u64CD\u4F5C\u548C\u7248\u672C\u63A7\u5236\u529F\u80FD"
    },
    type: "stdio",
    command: "npx",
    args: ["-y", "@modelcontextprotocol/server-git@latest"],
    env: {},
    requiredFor: [],
    optionalFor: ["all"],
    installCheck: "npx @modelcontextprotocol/server-git@latest --version",
    installCommand: "npm install -g @modelcontextprotocol/server-git",
    category: "git",
    platforms: ["windows", "macos", "linux", "wsl"],
    requiredCommands: ["git", "node", "npm"]
  },
  // ============================================================================
  // Testing Frameworks
  // ============================================================================
  "playwright-mcp": {
    id: "playwright-mcp",
    name: {
      "en": "Playwright MCP Server",
      "zh-CN": "Playwright MCP \u670D\u52A1\u5668"
    },
    description: {
      "en": "End-to-end testing and browser automation through MCP protocol",
      "zh-CN": "\u901A\u8FC7 MCP \u534F\u8BAE\u63D0\u4F9B\u7AEF\u5230\u7AEF\u6D4B\u8BD5\u548C\u6D4F\u89C8\u5668\u81EA\u52A8\u5316\u529F\u80FD"
    },
    type: "stdio",
    command: "npx",
    args: ["-y", "@playwright/mcp-server@latest"],
    env: {},
    requiredFor: [],
    optionalFor: ["testing", "e2e", "web", "automation"],
    installCheck: "npx @playwright/mcp-server@latest --version",
    installCommand: "npm install -g @playwright/mcp-server",
    category: "testing",
    platforms: ["windows", "macos", "linux"],
    requiresGui: false,
    // Can run headless
    requiredCommands: ["node", "npm"]
  },
  // ============================================================================
  // Browser Automation
  // ============================================================================
  "puppeteer-mcp": {
    id: "puppeteer-mcp",
    name: {
      "en": "Puppeteer MCP Server",
      "zh-CN": "Puppeteer MCP \u670D\u52A1\u5668"
    },
    description: {
      "en": "Chrome/Chromium browser automation and web scraping through MCP protocol",
      "zh-CN": "\u901A\u8FC7 MCP \u534F\u8BAE\u63D0\u4F9B Chrome/Chromium \u6D4F\u89C8\u5668\u81EA\u52A8\u5316\u548C\u7F51\u9875\u6293\u53D6\u529F\u80FD"
    },
    type: "stdio",
    command: "npx",
    args: ["-y", "@modelcontextprotocol/server-puppeteer@latest"],
    env: {},
    requiredFor: [],
    optionalFor: ["web-scraping", "automation", "testing"],
    installCheck: "npx @modelcontextprotocol/server-puppeteer@latest --version",
    installCommand: "npm install -g @modelcontextprotocol/server-puppeteer",
    category: "browser",
    platforms: ["windows", "macos", "linux"],
    requiresGui: false,
    // Can run headless
    requiredCommands: ["node", "npm"]
  },
  // ============================================================================
  // Additional Language Servers
  // ============================================================================
  "vscode-json-language-server": {
    id: "vscode-json-language-server",
    name: {
      "en": "JSON Language Server",
      "zh-CN": "JSON \u8BED\u8A00\u670D\u52A1\u5668"
    },
    description: {
      "en": "JSON schema validation, completion, and formatting support",
      "zh-CN": "\u63D0\u4F9B JSON \u6A21\u5F0F\u9A8C\u8BC1\u3001\u81EA\u52A8\u8865\u5168\u548C\u683C\u5F0F\u5316\u652F\u6301"
    },
    type: "stdio",
    command: "vscode-json-language-server",
    args: ["--stdio"],
    env: {},
    requiredFor: [],
    optionalFor: ["json", "configuration", "api"],
    installCheck: "vscode-json-language-server --version",
    installCommand: "npm install -g vscode-langservers-extracted",
    category: "language",
    platforms: ["windows", "macos", "linux", "wsl"],
    requiredCommands: ["node", "npm"]
  },
  "yaml-language-server": {
    id: "yaml-language-server",
    name: {
      "en": "YAML Language Server",
      "zh-CN": "YAML \u8BED\u8A00\u670D\u52A1\u5668"
    },
    description: {
      "en": "YAML schema validation, completion, and syntax highlighting",
      "zh-CN": "\u63D0\u4F9B YAML \u6A21\u5F0F\u9A8C\u8BC1\u3001\u81EA\u52A8\u8865\u5168\u548C\u8BED\u6CD5\u9AD8\u4EAE"
    },
    type: "stdio",
    command: "yaml-language-server",
    args: ["--stdio"],
    env: {},
    requiredFor: [],
    optionalFor: ["yaml", "kubernetes", "docker-compose", "ci-cd"],
    installCheck: "yaml-language-server --version",
    installCommand: "npm install -g yaml-language-server",
    category: "language",
    platforms: ["windows", "macos", "linux", "wsl"],
    requiredCommands: ["node", "npm"]
  }
};
function isTemplateCompatible(template, platform) {
  if (!template.platforms || template.platforms.length === 0) {
    return true;
  }
  if (!platform) {
    const process = globalThis.process;
    if (!process)
      return true;
    const platformMap = {
      win32: "windows",
      darwin: "macos",
      linux: "linux"
    };
    platform = platformMap[process.platform] || "linux";
    if (platform === "linux" && process.env.WSL_DISTRO_NAME) {
      platform = "wsl";
    }
  }
  return template.platforms.includes(platform);
}
function getCompatibleMcpServiceTemplates(platform) {
  return Object.values(mcpServiceTemplates).filter(
    (template) => isTemplateCompatible(template, platform)
  );
}

const SERVICE_TIERS = {
  core: ["typescript-language-server", "python-lsp-server", "gopls", "rust-analyzer"],
  ondemand: ["eslint-mcp", "prettier-mcp", "git-mcp"],
  scenario: ["playwright-mcp", "puppeteer-mcp"]
};
async function ccjkMcp(options = {}) {
  const startTime = Date.now();
  await ensureI18nInitialized();
  if (options.lang) {
    i18n.changeLanguage(options.lang);
  }
  const isZh = i18n.language === "zh-CN";
  const projectPath = cwd();
  const result = {
    success: false,
    project: {
      type: "unknown",
      languages: [],
      frameworks: []
    },
    services: [],
    installed: [],
    skipped: [],
    failed: [],
    duration: 0,
    configPath: join(CLAUDE_DIR, "mcp.json")
  };
  try {
    consola.info(isZh ? "\u{1F50D} \u5206\u6790\u9879\u76EE\u4E2D..." : "\u{1F50D} Analyzing project...");
    const analysis = await analyzeProject(projectPath, {
      analyzeTransitiveDeps: false
      // Use default maxFilesToScan of 10000 for better large project support
    });
    result.project.type = analysis.projectType;
    result.project.languages = analysis.languages.map((l) => l.language);
    result.project.frameworks = analysis.frameworks.map((f) => f.name);
    if (!options.json) {
      console.log("");
      console.log(a.green(`   ${isZh ? "\u68C0\u6D4B\u5230" : "Detected"}: ${a.bold(analysis.projectType)}`));
      console.log(a.dim(`   ${isZh ? "\u8BED\u8A00" : "Languages"}: ${analysis.languages.map((l) => l.language).join(", ")}`));
      if (analysis.frameworks.length > 0) {
        console.log(a.dim(`   ${isZh ? "\u6846\u67B6" : "Frameworks"}: ${analysis.frameworks.map((f) => f.name).join(", ")}`));
      }
      console.log("");
    }
    const recommendedServices = await getRecommendedServices(analysis, options);
    const availableServices = filterServicesByTier(recommendedServices, options.tier);
    const selectedServices = filterServicesByExclusion(availableServices, options.exclude);
    if (!options.json) {
      console.log(a.bold.cyan(`${isZh ? "\u{1F527} \u63A8\u8350\u7684 MCP \u670D\u52A1" : "\u{1F527} Recommended MCP Services"} (${selectedServices.length} ${isZh ? "\u4E2A" : "found"}):
`));
      const coreServices = selectedServices.filter((s) => SERVICE_TIERS.core.includes(s.id));
      const ondemandServices = selectedServices.filter((s) => SERVICE_TIERS.ondemand.includes(s.id));
      const scenarioServices = selectedServices.filter((s) => SERVICE_TIERS.scenario.includes(s.id));
      if (coreServices.length > 0) {
        console.log(a.bold(`${isZh ? "\u6838\u5FC3\u670D\u52A1" : "Core Services"}:`));
        coreServices.forEach((service) => {
          const installed = isServiceInstalled(service.id);
          const status = installed ? a.green("\u2705") : a.yellow("\u2B55");
          const _name = isZh ? service.name["zh-CN"] : service.name.en;
          const desc = isZh ? service.description["zh-CN"] : service.description.en;
          console.log(`  ${status} ${a.bold(service.id.padEnd(30))} - ${desc}`);
        });
        console.log("");
      }
      if (ondemandServices.length > 0) {
        console.log(a.bold(`${isZh ? "\u6309\u9700\u670D\u52A1" : "On-Demand Services"}:`));
        ondemandServices.forEach((service) => {
          const installed = isServiceInstalled(service.id);
          const status = installed ? a.green("\u2705") : a.yellow("\u2B55");
          const _name = isZh ? service.name["zh-CN"] : service.name.en;
          const desc = isZh ? service.description["zh-CN"] : service.description.en;
          console.log(`  ${status} ${a.bold(service.id.padEnd(30))} - ${desc}`);
        });
        console.log("");
      }
      if (scenarioServices.length > 0) {
        console.log(a.bold(`${isZh ? "\u573A\u666F\u670D\u52A1" : "Scenario Services"}:`));
        scenarioServices.forEach((service) => {
          const installed = isServiceInstalled(service.id);
          const status = installed ? a.green("\u2705") : a.yellow("\u2B55");
          const _name = isZh ? service.name["zh-CN"] : service.name.en;
          const desc = isZh ? service.description["zh-CN"] : service.description.en;
          console.log(`  ${status} ${a.bold(service.id.padEnd(30))} - ${desc}`);
        });
        console.log("");
      }
    }
    let servicesToInstall = selectedServices;
    if (options.interactive !== false && !options.json) {
      const { confirm } = await inquirer.prompt([{
        type: "confirm",
        name: "confirm",
        message: `${isZh ? "\u5B89\u88C5\u63A8\u8350\u670D\u52A1" : "Install recommended services"}?`,
        default: true
      }]);
      if (!confirm) {
        consola.warn(isZh ? "\u64CD\u4F5C\u5DF2\u53D6\u6D88" : "Operation cancelled");
        result.success = true;
        result.duration = Date.now() - startTime;
        return result;
      }
      const { selected } = await inquirer.prompt([{
        type: "checkbox",
        name: "selected",
        message: isZh ? "\u9009\u62E9\u8981\u5B89\u88C5\u7684\u670D\u52A1" : "Select services to install",
        choices: selectedServices.map((s) => ({
          name: `${s.id} - ${isZh ? s.name["zh-CN"] : s.name.en}`,
          value: s.id,
          checked: true
        }))
      }]);
      servicesToInstall = selectedServices.filter((s) => selected.includes(s.id));
    }
    const alreadyInstalled = [];
    if (!options.force) {
      servicesToInstall = servicesToInstall.filter((s) => {
        const installed = isServiceInstalled(s.id);
        if (installed) {
          alreadyInstalled.push(s.id);
        }
        return !installed;
      });
    }
    result.skipped.push(...alreadyInstalled);
    if (servicesToInstall.length === 0) {
      if (!options.json) {
        console.log(a.green(isZh ? "\u2705 \u6240\u6709\u670D\u52A1\u5DF2\u5B89\u88C5" : "\u2705 All services already installed"));
      }
      result.success = true;
      result.duration = Date.now() - startTime;
      return result;
    }
    if (options.dryRun) {
      if (!options.json) {
        console.log(a.yellow(isZh ? "\n\u{1F50D} Dry run \u6A21\u5F0F - \u9884\u89C8\u5B89\u88C5\u8BA1\u5212" : "\n\u{1F50D} Dry run mode - Installation preview"));
        console.log("");
        servicesToInstall.forEach((service) => {
          const name = isZh ? service.name["zh-CN"] : service.name.en;
          console.log(`  \u2022 ${service.id} (${name})`);
        });
        console.log("");
      }
      result.success = true;
      result.duration = Date.now() - startTime;
      return result;
    }
    if (!options.json) {
      console.log(a.bold.cyan(`${isZh ? "\u{1F4E6} \u5B89\u88C5\u4F9D\u8D56\u4E2D..." : "\u{1F4E6} Installing dependencies..."}
`));
    }
    for (const service of servicesToInstall) {
      const installResult = await installServiceDependencies(service, options);
      result.services.push(installResult);
      if (installResult.status === "installed") {
        result.installed.push(service.id);
      } else if (installResult.status === "skipped") {
        result.skipped.push(service.id);
      } else {
        result.failed.push(service.id);
      }
      if (!options.json) {
        const status = installResult.status === "installed" ? a.green("\u2713") : installResult.status === "skipped" ? a.yellow("\u25CB") : a.red("\u2717");
        const name = isZh ? service.name["zh-CN"] : service.name.en;
        console.log(`  ${status} ${service.id} (${name})`);
        if (installResult.error) {
          console.log(a.red(`    ${installResult.error}`));
        }
      }
    }
    if (result.installed.length > 0) {
      if (!options.json) {
        console.log("");
        console.log(a.bold.cyan(`${isZh ? "\u2699\uFE0F  \u914D\u7F6E MCP \u670D\u52A1\u4E2D..." : "\u2699\uFE0F  Configuring MCP services..."}
`));
      }
      backupMcpConfig();
      const config = readMcpConfig() || { mcpServers: {} };
      const newServers = {};
      for (const serviceId of result.installed) {
        const service = mcpServiceTemplates[serviceId] || servicesToInstall.find((s) => s.id === serviceId);
        if (service) {
          newServers[serviceId] = {
            type: service.type,
            command: service.command,
            args: service.args,
            env: service.env
          };
        }
      }
      const mergedConfig = mergeMcpServers(config, newServers);
      writeMcpConfig(mergedConfig);
      if (!options.json) {
        result.installed.forEach((serviceId) => {
          const service = mcpServiceTemplates[serviceId] || servicesToInstall.find((s) => s.id === serviceId);
          const name = service ? isZh ? service.name["zh-CN"] : service.name.en : serviceId;
          console.log(`  ${a.green("\u2713")} ${serviceId} (${name})`);
        });
      }
    }
    if (!options.skipVerification && result.installed.length > 0) {
      if (!options.json) {
        console.log("");
        console.log(a.bold.cyan(`${isZh ? "\u{1F50D} \u9A8C\u8BC1\u670D\u52A1..." : "\u{1F50D} Verifying services..."}
`));
      }
      for (const serviceId of result.installed) {
        const service = mcpServiceTemplates[serviceId] || servicesToInstall.find((s) => s.id === serviceId);
        const verified = service ? await verifyService(service) : false;
        if (!options.json) {
          const name = service ? isZh ? service.name["zh-CN"] : service.name.en : serviceId;
          const status = verified ? a.green("\u2713") : a.red("\u2717");
          console.log(`  ${status} ${serviceId} (${name})`);
        }
      }
    }
    result.success = result.failed.length === 0;
    if (!options.json) {
      console.log("");
      if (result.success) {
        console.log(a.green.bold(`${isZh ? `\u2705 \u6210\u529F\u914D\u7F6E ${result.installed.length} \u4E2A MCP \u670D\u52A1\uFF01` : `\u2705 Successfully configured ${result.installed.length} MCP service(s)!`}`));
      } else {
        console.log(a.yellow.bold(`${isZh ? `\u26A0\uFE0F \u90E8\u5206\u670D\u52A1\u914D\u7F6E\u5931\u8D25` : `\u26A0\uFE0F Some services failed to configure`}`));
      }
      console.log("");
      console.log(a.bold(isZh ? "\u4E0B\u4E00\u6B65:" : "Next steps:"));
      console.log(`  \u2022 ${isZh ? "\u4F7F\u7528 /ccjk:skills \u5B89\u88C5\u6280\u80FD" : "Use /ccjk:skills to install skills"}`);
      console.log(`  \u2022 ${isZh ? "\u4F7F\u7528 /ccjk:agents \u521B\u5EFA\u4EE3\u7406" : "Use /ccjk:agents to create agents"}`);
      console.log(`  \u2022 ${isZh ? "\u91CD\u542F Claude Code \u4EE5\u5E94\u7528\u66F4\u6539" : "Restart Claude Code to apply changes"}`);
      console.log("");
    }
    result.duration = Date.now() - startTime;
    return result;
  } catch (error) {
    consola.error(isZh ? "MCP \u670D\u52A1\u914D\u7F6E\u5931\u8D25" : "MCP service configuration failed", error);
    result.success = false;
    result.duration = Date.now() - startTime;
    return result;
  }
}
async function getRecommendedServices(analysis, options) {
  const services = [];
  const projectType = analysis.projectType.toLowerCase();
  const languages = analysis.languages.map((l) => l.language.toLowerCase());
  const frameworks = analysis.frameworks.map((f) => f.name.toLowerCase());
  const isZh = i18n.language === "zh-CN";
  try {
    const templatesClient = getTemplatesClient({ language: isZh ? "zh-CN" : "en" });
    const cloudMcpServices = await templatesClient.getOfficialMcpServers();
    if (cloudMcpServices.length > 0) {
      consola.success(isZh ? `\u4ECE\u4E91\u7AEF\u83B7\u53D6 ${cloudMcpServices.length} \u4E2A MCP \u670D\u52A1` : `Fetched ${cloudMcpServices.length} MCP services from cloud`);
      const relevantServices = cloudMcpServices.filter((mcp) => {
        const tags = mcp.tags || [];
        const category = mcp.category || "";
        const compatibility = mcp.compatibility || {};
        return tags.some((tag) => languages.includes(tag) || frameworks.includes(tag) || projectType.includes(tag)) || (compatibility.languages || []).some((lang) => languages.includes(lang.toLowerCase())) || (compatibility.frameworks || []).some((fw) => frameworks.includes(fw.toLowerCase())) || category === "core";
      });
      for (const mcp of relevantServices.length > 0 ? relevantServices : cloudMcpServices.slice(0, 10)) {
        const localTemplate = mcpServiceTemplates[mcp.id] || mcpServiceTemplates[mcp.name_en.toLowerCase().replace(/\s+/g, "-")];
        if (localTemplate) {
          services.push(localTemplate);
        } else {
          const cloudTemplate = {
            id: mcp.id || mcp.name_en.toLowerCase().replace(/\s+/g, "-"),
            name: {
              "en": mcp.name_en,
              "zh-CN": mcp.name_zh_cn || mcp.name_en
            },
            description: {
              "en": mcp.description_en || "",
              "zh-CN": mcp.description_zh_cn || mcp.description_en || ""
            },
            type: "stdio",
            command: mcp.npm_package ? "npx" : "node",
            args: mcp.npm_package ? ["-y", mcp.npm_package] : [],
            installCommand: mcp.install_command || `npm install -g ${mcp.npm_package || mcp.id}`,
            installCheck: mcp.npm_package ? `npx ${mcp.npm_package} --version` : "echo ok",
            category: "tooling",
            requiredFor: [],
            optionalFor: ["all"],
            env: {}
          };
          services.push(cloudTemplate);
        }
      }
      if (services.length > 0) {
        return services;
      }
    }
  } catch (_error) {
    consola.warn(isZh ? "\u4E91\u7AEF\u83B7\u53D6\u5931\u8D25\uFF0C\u4F7F\u7528\u672C\u5730\u6A21\u677F" : "Cloud fetch failed, using local templates");
  }
  const allServices = getCompatibleMcpServiceTemplates();
  for (const service of allServices) {
    if (options.services && options.services.length > 0) {
      if (options.services.includes(service.id)) {
        services.push(service);
      }
      continue;
    }
    if (options.exclude && options.exclude.includes(service.id)) {
      continue;
    }
    if (service.requiredFor.includes(projectType) || service.requiredFor.includes("all")) {
      services.push(service);
      continue;
    }
    if (service.optionalFor.includes(projectType) || service.optionalFor.includes("all")) {
      services.push(service);
      continue;
    }
    for (const lang of languages) {
      if (service.requiredFor.includes(lang) || service.optionalFor.includes(lang)) {
        services.push(service);
        break;
      }
    }
  }
  const uniqueServices = Array.from(
    new Map(services.map((s) => [s.id, s])).values()
  );
  return uniqueServices;
}
function filterServicesByTier(services, tier) {
  if (!tier || tier === "all") {
    return services;
  }
  const tierServices = SERVICE_TIERS[tier];
  return services.filter((s) => tierServices.includes(s.id));
}
function filterServicesByExclusion(services, exclude) {
  if (!exclude || exclude.length === 0) {
    return services;
  }
  return services.filter((s) => !exclude.includes(s.id));
}
function isServiceInstalled(serviceId) {
  const config = readMcpConfig();
  return config?.mcpServers?.[serviceId] !== void 0;
}
async function installServiceDependencies(service, options) {
  const result = {
    id: service.id,
    name: i18n.language === "zh-CN" ? service.name["zh-CN"] : service.name.en,
    status: "installed"
  };
  try {
    if (isServiceInstalled(service.id) && !options.force) {
      result.status = "skipped";
      return result;
    }
    const commandExists2 = await checkCommandExists(service.command);
    if (commandExists2) {
      result.dependenciesInstalled = false;
      return result;
    }
    if (options.autoInstall) {
      consola.info(`Installing ${service.id}...`);
      const { exec } = await import('./main.mjs');
      const [cmd, ...args] = service.installCommand.split(" ");
      await exec(cmd, args);
      result.dependenciesInstalled = true;
    } else {
      result.status = "skipped";
      result.error = i18n.language === "zh-CN" ? "\u4F9D\u8D56\u672A\u5B89\u88C5\uFF0C\u4F7F\u7528 --auto-install \u81EA\u52A8\u5B89\u88C5" : "Dependencies not installed, use --auto-install to install automatically";
    }
    return result;
  } catch (error) {
    result.status = "failed";
    result.error = error instanceof Error ? error.message : String(error);
    return result;
  }
}
async function checkCommandExists(command) {
  try {
    const cmdName = command.split(" ")[0];
    return commandExists(cmdName);
  } catch {
    return false;
  }
}
async function verifyService(service) {
  try {
    const { exec } = await import('./main.mjs');
    const [cmd, ...args] = service.installCheck.split(" ");
    const result = await exec(cmd, args, { timeout: 5e3 });
    return result.exitCode === 0;
  } catch {
    return false;
  }
}
function formatResultAsJson(result) {
  return JSON.stringify(result, null, 2);
}
function formatResultForConsole(result) {
  const isZh = i18n.language === "zh-CN";
  const lines = [];
  lines.push(a.bold.cyan(isZh ? "\u{1F4CA} MCP \u670D\u52A1\u914D\u7F6E\u6458\u8981" : "\u{1F4CA} MCP Service Configuration Summary"));
  lines.push("");
  lines.push(`${a.bold(isZh ? "\u9879\u76EE\u7C7B\u578B" : "Project Type")}: ${result.project.type}`);
  lines.push(`${a.bold(isZh ? "\u8BED\u8A00" : "Languages")}: ${result.project.languages.join(", ")}`);
  if (result.project.frameworks.length > 0) {
    lines.push(`${a.bold(isZh ? "\u6846\u67B6" : "Frameworks")}: ${result.project.frameworks.join(", ")}`);
  }
  lines.push("");
  lines.push(a.bold(isZh ? "\u5B89\u88C5\u7684\u670D\u52A1" : "Installed Services"));
  result.installed.forEach((id) => {
    lines.push(`  ${a.green("\u2713")} ${id}`);
  });
  lines.push("");
  if (result.skipped.length > 0) {
    lines.push(a.bold(isZh ? "\u8DF3\u8FC7\u7684\u670D\u52A1" : "Skipped Services"));
    result.skipped.forEach((id) => {
      lines.push(`  ${a.yellow("\u25CB")} ${id}`);
    });
    lines.push("");
  }
  if (result.failed.length > 0) {
    lines.push(a.bold(isZh ? "\u5931\u8D25\u7684\u670D\u52A1" : "Failed Services"));
    result.failed.forEach((id) => {
      lines.push(`  ${a.red("\u2717")} ${id}`);
    });
    lines.push("");
  }
  lines.push(`${a.bold(isZh ? "\u8017\u65F6" : "Duration")}: ${result.duration}ms`);
  lines.push(`${a.bold(isZh ? "\u914D\u7F6E\u6587\u4EF6" : "Config File")}: ${result.configPath}`);
  return lines.join("\n");
}

export { ccjkMcp, formatResultAsJson, formatResultForConsole };
