import a from './index5.mjs';
import { c as consola, a as analyzeProject } from '../shared/ccjk.CoCHVXl3.mjs';
import { c as createCompleteCloudClient } from '../shared/ccjk.OJKHVSOb.mjs';
import { i18n, ensureI18nInitialized } from './index2.mjs';
import { createHash } from 'node:crypto';
import { promises, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { c as createDefaultGateway } from '../shared/ccjk.D0g2ABGg.mjs';
import { ccjkAgents } from './ccjk-agents.mjs';
import { ccjkHooks } from './ccjk-hooks.mjs';
import { ccjkMcp } from './ccjk-mcp.mjs';
import { ccjkSkills } from './ccjk-skills.mjs';
import { e as extractString } from '../shared/ccjk.C2jHOZVP.mjs';
import '../shared/ccjk.BAGoDD49.mjs';
import './index10.mjs';
import '../shared/ccjk.bQ7Dh1g4.mjs';
import 'tinyglobby';
import '../shared/ccjk.BBtCGd_g.mjs';
import './constants.mjs';
import 'node:os';
import 'node:process';
import 'node:url';
import '../shared/ccjk.D6ycHbak.mjs';
import '../shared/ccjk.CfKKcvWy.mjs';
import 'node:perf_hooks';
import './index6.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 'buffer';
import 'string_decoder';
import 'node:child_process';
import './claude-config.mjs';
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 './platform.mjs';
import './main.mjs';
import 'module';
import 'node:stream';
import '../shared/ccjk.i_vn-9C3.mjs';

const packageJson = JSON.parse(readFileSync(join(process.cwd(), "package.json"), "utf-8"));
const CCJK_VERSION = packageJson.version;
class CloudSetupOrchestrator {
  gateway;
  logger = consola.withTag("cloud-setup");
  startTime = Date.now();
  constructor(_options = {}) {
    this.gateway = createDefaultGateway();
  }
  /**
   * Execute cloud-powered setup
   */
  async executeCloudSetup(options) {
    this.logger.info("Starting cloud-powered setup");
    try {
      const analysis = await this.analyzeProject(options);
      const recommendations = await this.getCloudRecommendations(analysis, options);
      if (options.interactive !== false) {
        await this.displayRecommendationInsights(recommendations, options);
      }
      const confirmed = await this.getUserConfirmation(recommendations, options);
      if (!confirmed) {
        return {
          success: false,
          requestId: recommendations.insights ? "user-cancelled" : "no-recommendations",
          confidence: recommendations.confidence || 0,
          installed: { skills: [], mcpServices: [], agents: [], hooks: [] },
          skipped: { skills: [], mcpServices: [], agents: [], hooks: [] },
          failed: { skills: [], mcpServices: [], agents: [], hooks: [] },
          duration: Date.now() - this.startTime
        };
      }
      const templates = recommendations.source === "cloud" ? await this.downloadTemplates(recommendations, options) : {
        requestId: "local-templates-skipped",
        templates: {},
        notFound: []
      };
      const result = await this.executeInstallation(recommendations, templates, options);
      if (options.submitTelemetry !== false) {
        this.uploadTelemetry(result).catch(() => {
        });
      }
      if (options.generateReport) {
        result.reportPath = await this.generateReport(result, recommendations, options);
      }
      return result;
    } catch (error) {
      this.logger.error("Cloud setup failed:", error);
      throw error;
    }
  }
  /**
   * Analyze project with deep inspection
   */
  async analyzeProject(options) {
    if (options.interactive !== false) {
      console.log(a.bold(`
  ${i18n.t("cloud-setup:analyzingProject")}`));
    }
    const analysis = await analyzeProject(options.targetDir || process.cwd(), {
      analyzeTransitiveDeps: true
      // Use default maxFilesToScan of 10000 for better large project support
    });
    this.generateProjectFingerprint(analysis);
    if (options.interactive !== false) {
      this.displayProjectInfo(analysis);
    }
    return analysis;
  }
  /**
   * Generate project fingerprint
   */
  generateProjectFingerprint(analysis) {
    const hash = createHash("sha256");
    const directDeps = analysis.dependencies?.direct || [];
    const depNames = directDeps.map((d) => d.name).join(",");
    const devDepNames = directDeps.filter((d) => d.isDev).map((d) => d.name).join(",");
    const frameworkNames = analysis.frameworks?.map((f) => f.name).join(",") || "";
    const languageNames = analysis.languages?.map((l) => l.language).join(",") || "";
    hash.update(depNames);
    hash.update(devDepNames);
    hash.update(analysis.projectType || "");
    hash.update(frameworkNames);
    hash.update(languageNames);
    return hash.digest("hex");
  }
  /**
   * Display project information
   */
  displayProjectInfo(analysis) {
    console.log(`    ${a.dim(i18n.t("cloud-setup:projectType"))}: ${analysis.projectType}`);
    if (analysis.frameworks.length > 0) {
      console.log(`    ${a.dim(i18n.t("cloud-setup:frameworks"))}: ${analysis.frameworks.map((f) => f.name).join(", ")}`);
    }
    if (analysis.languages.length > 0) {
      console.log(`    ${a.dim(i18n.t("cloud-setup:languages"))}: ${analysis.languages.map((l) => l.language).join(", ")}`);
    }
  }
  /**
   * Get recommendations from cloud
   */
  async getCloudRecommendations(analysis, options) {
    if (options.useCloud === false) {
      return this.getLocalRecommendations(analysis);
    }
    if (options.interactive !== false) {
      console.log(`
  ${a.bold(i18n.t("cloud-setup:gettingRecommendations"))}`);
    }
    const request = {
      projectRoot: options.targetDir || process.cwd(),
      language: options.lang,
      ccjkVersion: CCJK_VERSION
    };
    if (analysis.dependencies?.direct && analysis.dependencies.direct.length > 0) {
      const deps = {};
      const devDeps = {};
      for (const dep of analysis.dependencies.direct) {
        if (dep.isDev) {
          devDeps[dep.name] = dep.version || "*";
        } else {
          deps[dep.name] = dep.version || "*";
        }
      }
      if (Object.keys(deps).length > 0) {
        request.dependencies = deps;
      }
      if (Object.keys(devDeps).length > 0) {
        request.devDependencies = devDeps;
      }
    }
    try {
      const response = await this.gateway.request(
        "analysis.projects",
        {
          method: "POST",
          body: request,
          timeout: 1e4
          // 10s timeout for cloud analysis
        }
      );
      if (!response.success || !response.data) {
        this.logger.warn("Cloud API returned error:", response.error);
        return this.getLocalRecommendations(analysis);
      }
      const data = response.data;
      const fingerprint = this.generateProjectFingerprint(analysis);
      const recommendations = {
        source: "cloud",
        skills: data.recommendations.filter((r) => r.category === "skill"),
        mcpServices: data.recommendations.filter((r) => r.category === "mcp"),
        agents: data.recommendations.filter((r) => r.category === "agent"),
        hooks: data.recommendations.filter((r) => r.category === "hook"),
        confidence: this.calculateConfidence(data.recommendations),
        fingerprint,
        insights: this.extractInsights(data)
      };
      return recommendations;
    } catch (_error) {
      this.logger.warn("Failed to get cloud recommendations, using local fallback");
      return this.getLocalRecommendations(analysis);
    }
  }
  /**
   * Check if a dependency exists in the analysis
   * Handles both Map<string, DependencyInfo> and DependencyNode[] formats
   */
  hasDependency(analysis, name, isDev = false) {
    const deps = analysis.dependencies;
    if (!deps)
      return false;
    if (Array.isArray(deps.direct)) {
      const nodeList = deps.direct;
      return nodeList.some((d) => d.name === name && (isDev ? d.isDev : !d.isDev));
    }
    return false;
  }
  /**
   * Check if a framework is detected in the analysis
   */
  hasFramework(analysis, name) {
    if (!analysis.frameworks)
      return false;
    if (Array.isArray(analysis.frameworks) && analysis.frameworks.length > 0) {
      const first = analysis.frameworks[0];
      if (typeof first === "object" && "name" in first) {
        return analysis.frameworks.some((f) => f.name?.toLowerCase() === name.toLowerCase());
      }
      if (typeof first === "string") {
        return analysis.frameworks.includes(name);
      }
    }
    return false;
  }
  /**
   * Check if a language is detected in the analysis
   */
  hasLanguage(analysis, name) {
    if (!analysis.languages)
      return false;
    if (Array.isArray(analysis.languages) && analysis.languages.length > 0) {
      const first = analysis.languages[0];
      if (typeof first === "object" && "language" in first) {
        return analysis.languages.some((l) => l.language?.toLowerCase() === name.toLowerCase());
      }
      if (typeof first === "string") {
        return analysis.languages.includes(name);
      }
    }
    return false;
  }
  /**
   * Get local fallback recommendations
   */
  getLocalRecommendations(analysis) {
    const recommendations = [];
    if (this.hasDependency(analysis, "typescript", true) || this.hasLanguage(analysis, "typescript")) {
      recommendations.push({
        id: "ts-best-practices",
        name: { "en": "TypeScript Best Practices", "zh-CN": "TypeScript \u6700\u4F73\u5B9E\u8DF5" },
        description: { "en": "Essential for TypeScript 5.3+ strict mode", "zh-CN": "TypeScript 5.3+ \u4E25\u683C\u6A21\u5F0F\u5FC5\u5907" },
        category: "skill",
        relevanceScore: 0.98,
        tags: ["typescript", "type-checking"]
      });
    }
    if (this.hasDependency(analysis, "react") || this.hasFramework(analysis, "react")) {
      recommendations.push({
        id: "react-design-patterns",
        name: { "en": "React Design Patterns", "zh-CN": "React \u8BBE\u8BA1\u6A21\u5F0F" },
        description: { "en": "React 18+ hooks and composition", "zh-CN": "React 18+ Hooks \u548C\u7EC4\u5408" },
        category: "skill",
        relevanceScore: 0.95,
        tags: ["react", "hooks", "frontend"]
      });
    }
    if (this.hasDependency(analysis, "next") || this.hasFramework(analysis, "next") || this.hasFramework(analysis, "nextjs")) {
      recommendations.push({
        id: "nextjs-optimization",
        name: { "en": "Next.js Optimization", "zh-CN": "Next.js \u4F18\u5316" },
        description: { "en": "App router and server components", "zh-CN": "App Router \u548C\u670D\u52A1\u5668\u7EC4\u4EF6" },
        category: "skill",
        relevanceScore: 0.92,
        tags: ["nextjs", "ssr", "performance"]
      });
    }
    if (this.hasDependency(analysis, "vue") || this.hasFramework(analysis, "vue")) {
      recommendations.push({
        id: "vue-design-patterns",
        name: { "en": "Vue Design Patterns", "zh-CN": "Vue \u8BBE\u8BA1\u6A21\u5F0F" },
        description: { "en": "Vue 3 Composition API patterns", "zh-CN": "Vue 3 \u7EC4\u5408\u5F0F API \u6A21\u5F0F" },
        category: "skill",
        relevanceScore: 0.95,
        tags: ["vue", "composition-api", "frontend"]
      });
    }
    if (this.hasDependency(analysis, "express") || this.hasDependency(analysis, "fastify") || this.hasFramework(analysis, "express")) {
      recommendations.push({
        id: "nodejs-workflow",
        name: { "en": "Node.js Workflow", "zh-CN": "Node.js \u5DE5\u4F5C\u6D41" },
        description: { "en": "Node.js development tools", "zh-CN": "Node.js \u5F00\u53D1\u5DE5\u5177" },
        category: "skill",
        relevanceScore: 0.9,
        tags: ["nodejs", "backend"]
      });
    }
    if (this.hasDependency(analysis, "@nestjs/core") || this.hasFramework(analysis, "nest") || this.hasFramework(analysis, "nestjs")) {
      recommendations.push({
        id: "nestjs-workflow",
        name: { "en": "NestJS Workflow", "zh-CN": "NestJS \u5DE5\u4F5C\u6D41" },
        description: { "en": "NestJS backend development", "zh-CN": "NestJS \u540E\u7AEF\u5F00\u53D1" },
        category: "skill",
        relevanceScore: 0.92,
        tags: ["nestjs", "backend", "typescript"]
      });
    }
    if (this.hasLanguage(analysis, "python")) {
      recommendations.push({
        id: "python-workflow",
        name: { "en": "Python Workflow", "zh-CN": "Python \u5DE5\u4F5C\u6D41" },
        description: { "en": "Python development best practices", "zh-CN": "Python \u5F00\u53D1\u6700\u4F73\u5B9E\u8DF5" },
        category: "skill",
        relevanceScore: 0.88,
        tags: ["python", "backend"]
      });
    }
    const fingerprint = this.generateProjectFingerprint(analysis);
    return {
      source: "local",
      skills: recommendations.filter((r) => r.category === "skill"),
      mcpServices: recommendations.filter((r) => r.category === "mcp"),
      agents: recommendations.filter((r) => r.category === "agent"),
      hooks: recommendations.filter((r) => r.category === "hook"),
      confidence: 0.7,
      // Local fallback has lower confidence
      fingerprint,
      insights: {
        insights: [],
        productivityImprovements: [],
        nextRecommendations: []
      }
    };
  }
  /**
   * Calculate confidence score
   */
  calculateConfidence(recommendations) {
    if (recommendations.length === 0)
      return 0;
    const avgScore = recommendations.reduce((sum, r) => sum + r.relevanceScore, 0) / recommendations.length;
    return Math.round(avgScore * 100);
  }
  /**
   * Extract insights from response
   */
  extractInsights(_response) {
    return {
      insights: [
        i18n.t("cloud-setup:cloudRecommendationsGenerated")
      ],
      productivityImprovements: [],
      nextRecommendations: [],
      communityStats: {
        similarProjects: 0,
        topInstallations: []
      }
    };
  }
  /**
   * Display recommendation insights
   */
  async displayRecommendationInsights(recommendations, options) {
    if (options.interactive === false)
      return;
    console.log(`
  ${a.bold(i18n.t("cloud-setup:cloudRecommendations"))} ${a.dim(`(${i18n.t("cloud-setup:confidence")} ${recommendations.confidence}%)`)}`);
    console.log("");
    if (recommendations.skills.length > 0) {
      console.log(`  ${a.bold(i18n.t("cloud-setup:skills"))} (${recommendations.skills.length}):`);
      for (const skill of recommendations.skills) {
        const confidence = options.showConfidence ? ` [${Math.round(skill.relevanceScore * 100)}%]` : "";
        const skillName = extractString(skill.name, skill.id, i18n.language);
        const skillDesc = extractString(skill.description, "", i18n.language);
        const reason = options.showRecommendationReason && skillDesc ? ` - ${skillDesc}` : "";
        console.log(`    ${a.green("\u2713")} ${skillName}${a.dim(confidence)}${a.dim(reason)}`);
      }
    }
    if (recommendations.mcpServices.length > 0) {
      console.log(`
  ${a.bold(i18n.t("cloud-setup:mcpServices"))} (${recommendations.mcpServices.length}):`);
      for (const service of recommendations.mcpServices) {
        const confidence = options.showConfidence ? ` [${Math.round(service.relevanceScore * 100)}%]` : "";
        const serviceName = extractString(service.name, service.id, i18n.language);
        const serviceDesc = extractString(service.description, "", i18n.language);
        const reason = options.showRecommendationReason && serviceDesc ? ` - ${serviceDesc}` : "";
        console.log(`    ${a.green("\u2713")} ${serviceName}${a.dim(confidence)}${a.dim(reason)}`);
      }
    }
    if (recommendations.agents.length > 0) {
      console.log(`
  ${a.bold(i18n.t("cloud-setup:agents"))} (${recommendations.agents.length}):`);
      for (const agent of recommendations.agents) {
        const confidence = options.showConfidence ? ` [${Math.round(agent.relevanceScore * 100)}%]` : "";
        const agentName = extractString(agent.name, agent.id, i18n.language);
        const agentDesc = extractString(agent.description, "", i18n.language);
        const reason = options.showRecommendationReason && agentDesc ? ` - ${agentDesc}` : "";
        console.log(`    ${a.green("\u2713")} ${agentName}${a.dim(confidence)}${a.dim(reason)}`);
      }
    }
    if (recommendations.hooks.length > 0) {
      console.log(`
  ${a.bold(i18n.t("cloud-setup:hooks"))} (${recommendations.hooks.length}):`);
      for (const hook of recommendations.hooks) {
        const confidence = options.showConfidence ? ` [${Math.round(hook.relevanceScore * 100)}%]` : "";
        const hookName = extractString(hook.name, hook.id, i18n.language);
        const hookDesc = extractString(hook.description, "", i18n.language);
        const reason = options.showRecommendationReason && hookDesc ? ` - ${hookDesc}` : "";
        console.log(`    ${a.green("\u2713")} ${hookName}${a.dim(confidence)}${a.dim(reason)}`);
      }
    }
    if (recommendations.insights?.insights && recommendations.insights.insights.length > 0) {
      console.log(`
  ${a.bold(i18n.t("cloud-setup:insights"))}:`);
      for (const insight of recommendations.insights.insights) {
        console.log(`    ${a.cyan("\u{1F4A1}")} ${insight}`);
      }
    }
    if (recommendations.insights?.productivityImprovements && recommendations.insights.productivityImprovements.length > 0) {
      console.log(`
  ${a.bold(i18n.t("cloud-setup:productivityImprovements"))}:`);
      for (const improvement of recommendations.insights.productivityImprovements) {
        console.log(`    ${a.green("\u2191")} ${improvement.resource}: +${improvement.improvement}% ${improvement.reason}`);
      }
    }
  }
  /**
   * Get user confirmation
   */
  async getUserConfirmation(recommendations, options) {
    if (options.interactive === false)
      return true;
    const totalResources = recommendations.skills.length + recommendations.mcpServices.length + recommendations.agents.length + recommendations.hooks.length;
    if (totalResources === 0) {
      console.log(`
  ${a.yellow(i18n.t("cloud-setup:noRecommendations"))}`);
      return false;
    }
    try {
      const inquirerModule = await import('./index6.mjs').then(function (n) { return n.c; });
      const inquirer = inquirerModule.default || inquirerModule;
      const { confirm } = await inquirer.prompt([
        {
          type: "confirm",
          name: "confirm",
          message: i18n.t("cloud-setup:installResources", { count: totalResources }),
          default: true
        }
      ]);
      return confirm;
    } catch (error) {
      this.logger.error("Failed to prompt user:", error);
      return true;
    }
  }
  /**
   * Download templates in batch
   */
  async downloadTemplates(recommendations, options) {
    if (options.interactive !== false) {
      console.log(`
  ${a.bold(i18n.t("cloud-setup:downloadingTemplates"))}`);
    }
    const allRecommendations = [
      ...recommendations.skills,
      ...recommendations.mcpServices,
      ...recommendations.agents,
      ...recommendations.hooks
    ];
    const templateIds = allRecommendations.map((r) => r.id);
    try {
      const response = await this.gateway.request(
        "templates.batch",
        {
          method: "POST",
          body: {
            ids: templateIds,
            language: options.lang
          },
          timeout: 15e3
          // 15s timeout for template download
        }
      );
      if (!response.success || !response.data) {
        throw new Error(response.error || "Template download failed");
      }
      const templates = response.data;
      if (options.interactive !== false) {
        console.log(`    ${a.green("\u2713")} ${i18n.t("cloud-setup:templatesDownloaded", { count: Object.keys(templates.templates).length })}`);
      }
      return templates;
    } catch (error) {
      this.logger.warn("Failed to download templates, continuing without templates:", error);
      return {
        requestId: "template-download-failed",
        templates: {},
        notFound: [
          ...recommendations.skills.map((r) => r.id),
          ...recommendations.mcpServices.map((r) => r.id),
          ...recommendations.agents.map((r) => r.id),
          ...recommendations.hooks.map((r) => r.id)
        ]
      };
    }
  }
  /**
   * Execute installation in parallel
   */
  async executeInstallation(recommendations, templates, options) {
    if (options.interactive !== false) {
      console.log(`
  ${a.bold(i18n.t("cloud-setup:installingResources"))}`);
    }
    const result = {
      success: true,
      requestId: "local-execution",
      confidence: recommendations.confidence,
      installed: { skills: [], mcpServices: [], agents: [], hooks: [] },
      skipped: { skills: [], mcpServices: [], agents: [], hooks: [] },
      failed: { skills: [], mcpServices: [], agents: [], hooks: [] },
      duration: 0,
      insights: recommendations.insights
    };
    if (recommendations.skills.length > 0) {
      await this.installSkills(recommendations.skills, result, options);
    }
    if (recommendations.mcpServices.length > 0) {
      await this.installMcpServices(recommendations.mcpServices, result, options);
    }
    if (recommendations.agents.length > 0) {
      await this.installAgents(recommendations.agents, result, options);
    }
    if (recommendations.hooks.length > 0) {
      await this.installHooks(recommendations.hooks, result, options);
    }
    result.duration = Math.max(Date.now() - this.startTime, 1);
    if (options.interactive !== false) {
      this.displaySummary(result, options);
    }
    return result;
  }
  /**
   * Install skills
   */
  async installSkills(skills, result, options) {
    if (options.interactive !== false) {
      console.log(`
  [1/4] ${i18n.t("cloud-setup:installingSkills")}...`);
    }
    const skillsOptions = {
      lang: options.lang,
      interactive: false,
      dryRun: options.dryRun,
      force: options.force,
      targetDir: options.targetDir
    };
    try {
      const skillIds = skills.map((s) => s.id);
      process.env.CCJK_SELECTED_SKILLS = JSON.stringify(skillIds);
      await ccjkSkills(skillsOptions);
      result.installed.skills = skillIds;
      if (options.interactive !== false) {
        console.log(`    ${a.green("\u2713")} ${skills.length}/${skills.length} (${((Date.now() - this.startTime) / 1e3).toFixed(1)}s)`);
      }
    } catch (error) {
      this.logger.error("Skills installation failed:", error);
      result.failed.skills = skills.map((s) => ({ id: s.id, error: String(error) }));
    }
  }
  /**
   * Install MCP services
   */
  async installMcpServices(services, result, options) {
    if (options.interactive !== false) {
      console.log(`
  [2/4] ${i18n.t("cloud-setup:configuringMcpServices")}...`);
    }
    const mcpOptions = {
      interactive: false,
      services: services.map((s) => s.id),
      dryRun: options.dryRun,
      force: options.force,
      lang: options.lang
    };
    try {
      await ccjkMcp(mcpOptions);
      result.installed.mcpServices = services.map((s) => s.id);
      if (options.interactive !== false) {
        console.log(`    ${a.green("\u2713")} ${services.length}/${services.length} (${((Date.now() - this.startTime) / 1e3).toFixed(1)}s)`);
      }
    } catch (error) {
      this.logger.error("MCP services installation failed:", error);
      result.failed.mcpServices = services.map((s) => ({ id: s.id, error: String(error) }));
    }
  }
  /**
   * Install agents
   */
  async installAgents(agents, result, options) {
    if (options.interactive !== false) {
      console.log(`
  [3/4] ${i18n.t("cloud-setup:creatingAgents")}...`);
    }
    const agentOptions = {
      lang: options.lang,
      dryRun: options.dryRun
      // Note: CcjkAgentsOptions doesn't support batch agent creation yet
      // We'll need to call ccjkAgents for each agent individually
    };
    try {
      await ccjkAgents(agentOptions);
      result.installed.agents = agents.map((a) => a.id);
      if (options.interactive !== false) {
        console.log(`    ${a.green("\u2713")} ${agents.length}/${agents.length} (${((Date.now() - this.startTime) / 1e3).toFixed(1)}s)`);
      }
    } catch (error) {
      this.logger.error("Agents installation failed:", error);
      result.failed.agents = agents.map((a) => ({ id: a.id, error: String(error) }));
    }
  }
  /**
   * Install hooks
   */
  async installHooks(hooks, result, options) {
    if (options.interactive !== false) {
      console.log(`
  [4/4] ${i18n.t("cloud-setup:settingUpHooks")}...`);
    }
    const hookOptions = {
      dryRun: options.dryRun
      // Note: CcjkHooksOptions doesn't have lang, interactive, hooks, or force properties
      // The ccjkHooks command will analyze and install hooks based on project analysis
    };
    try {
      await ccjkHooks(hookOptions);
      result.installed.hooks = hooks.map((h) => h.id);
      if (options.interactive !== false) {
        console.log(`    ${a.green("\u2713")} ${hooks.length}/${hooks.length} (${((Date.now() - this.startTime) / 1e3).toFixed(1)}s)`);
      }
    } catch (error) {
      this.logger.error("Hooks installation failed:", error);
      result.failed.hooks = hooks.map((h) => ({ id: h.id, error: String(error) }));
    }
  }
  /**
   * Display summary
   */
  displaySummary(result, options) {
    console.log("");
    console.log(a.green(`  ${i18n.t("cloud-setup:setupComplete")}`));
    const totalInstalled = result.installed.skills.length + result.installed.mcpServices.length + result.installed.agents.length + result.installed.hooks.length;
    console.log(`  ${i18n.t("cloud-setup:installedResources", { count: totalInstalled, duration: (result.duration / 1e3).toFixed(1) })}`);
    if (result.insights) {
      console.log(`
  ${a.bold(i18n.t("cloud-setup:cloudFeedback"))}`);
      for (const insight of result.insights.insights) {
        console.log(`    ${a.cyan("\u2022")} ${insight}`);
      }
    }
    console.log(`
  ${a.bold(i18n.t("cloud-setup:nextSteps"))}`);
    console.log(`    ${a.dim("\u2022")} ${i18n.t("cloud-setup:startCoding")}`);
    if (options.showRecommendationReason) {
      console.log(`    ${a.dim("\u2022")} ${i18n.t("cloud-setup:viewRecommendations")}`);
    }
    console.log(`    ${a.dim("\u2022")} ${i18n.t("cloud-setup:customizeSetup")}`);
    if (result.reportPath) {
      console.log(`
  ${a.dim(i18n.t("cloud-setup:reportGenerated", { path: result.reportPath }))}`);
    }
  }
  /**
   * Upload telemetry (non-blocking with retry budget)
   * Fire-and-forget: does not block setup completion
   */
  async uploadTelemetry(result) {
    const telemetry = {
      requestId: result.requestId,
      installation: {
        timestamp: Date.now(),
        duration: result.duration,
        selectedResources: [
          ...result.installed.skills.map((id) => ({ id, type: "skill", version: "1.0.0" })),
          ...result.installed.mcpServices.map((id) => ({ id, type: "mcp", version: "1.0.0" })),
          ...result.installed.agents.map((id) => ({ id, type: "agent", version: "1.0.0" })),
          ...result.installed.hooks.map((id) => ({ id, type: "hook", version: "1.0.0" }))
        ],
        skippedResources: [
          ...result.skipped.skills,
          ...result.skipped.mcpServices,
          ...result.skipped.agents,
          ...result.skipped.hooks
        ],
        failedResources: [
          ...result.failed.skills,
          ...result.failed.mcpServices,
          ...result.failed.agents,
          ...result.failed.hooks
        ]
      },
      clientInfo: {
        ccjkVersion: CCJK_VERSION,
        os: process.platform,
        nodeVersion: process.version
      },
      performance: {
        networkLatency: 0,
        cacheHit: false,
        retryCount: 0
      }
    };
    this.sendTelemetryWithRetry(telemetry, 3, 5e3).catch((error) => {
      this.logger.debug("Telemetry upload failed after retries (non-blocking):", error);
    });
  }
  /**
   * Send telemetry with retry budget
   * Private helper for non-blocking telemetry submission
   */
  async sendTelemetryWithRetry(telemetry, maxAttempts, timeout) {
    for (let attempt = 1; attempt <= maxAttempts; attempt++) {
      try {
        const timeoutPromise = new Promise((_, reject) => {
          setTimeout(() => reject(new Error("Telemetry timeout")), timeout);
        });
        const response = await Promise.race([
          this.gateway.request("telemetry.installation", {
            method: "POST",
            body: telemetry,
            timeout
          }),
          timeoutPromise
        ]);
        if (response.success) {
          this.logger.debug(`Telemetry uploaded successfully (attempt ${attempt}/${maxAttempts})`);
          return;
        }
        throw new Error(response.error || "Unknown telemetry error");
      } catch (error) {
        this.logger.debug(
          `Telemetry attempt ${attempt}/${maxAttempts} failed:`,
          error instanceof Error ? error.message : error
        );
        if (attempt === maxAttempts) {
          this.logger.debug("Telemetry failed after all retry attempts - giving up silently");
          return;
        }
        const delay = 100 * 2 ** (attempt - 1);
        await new Promise((resolve) => setTimeout(resolve, delay));
      }
    }
  }
  /**
   * Generate cloud insights report
   */
  async generateReport(result, recommendations, options) {
    const reportExtension = options.reportFormat === "json" ? "json" : options.reportFormat === "html" ? "html" : "md";
    const reportPath = join(
      process.cwd(),
      `ccjk-setup-report-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.${reportExtension}`
    );
    let content = "";
    if (options.reportFormat === "json") {
      content = JSON.stringify({
        timestamp: (/* @__PURE__ */ new Date()).toISOString(),
        result,
        recommendations,
        options
      }, null, 2);
    } else {
      content = `# CCJK Setup Report (Cloud-Enhanced)

`;
      content += `**Date**: ${(/* @__PURE__ */ new Date()).toLocaleString()}
`;
      content += `**Strategy**: ${options.strategy || "cloud-smart"}
`;
      content += `**Cloud Confidence**: ${result.confidence}%
`;
      content += `**Duration**: ${(result.duration / 1e3).toFixed(1)}s

`;
      content += `## Installed Resources (${Object.values(result.installed).flat().length})

`;
      if (result.installed.skills.length > 0) {
        content += `### Skills (${result.installed.skills.length})
`;
        for (const skill of result.installed.skills) {
          content += `- ${skill}
`;
        }
        content += "\n";
      }
      if (result.installed.mcpServices.length > 0) {
        content += `### MCP Services (${result.installed.mcpServices.length})
`;
        for (const service of result.installed.mcpServices) {
          content += `- ${service}
`;
        }
        content += "\n";
      }
      if (result.installed.agents.length > 0) {
        content += `### Agents (${result.installed.agents.length})
`;
        for (const agent of result.installed.agents) {
          content += `- ${agent}
`;
        }
        content += "\n";
      }
      if (result.installed.hooks.length > 0) {
        content += `### Hooks (${result.installed.hooks.length})
`;
        for (const hook of result.installed.hooks) {
          content += `- ${hook}
`;
        }
        content += "\n";
      }
      if (result.insights?.nextRecommendations && result.insights.nextRecommendations.length > 0) {
        content += `## Next Recommendations

`;
        for (const rec of result.insights.nextRecommendations) {
          content += `- ${rec}
`;
        }
      }
    }
    await promises.writeFile(reportPath, content, "utf-8");
    return reportPath;
  }
  /**
   * Execute with fallback
   */
  async executeWithFallback(options) {
    try {
      return await this.executeCloudSetup(options);
    } catch (error) {
      if (error.code === "ENOTFOUND" || error.code === "ECONNREFUSED") {
        console.warn(a.yellow(`
  ${i18n.t("cloud-setup:cloudUnavailable")}`));
        console.warn(`  ${i18n.t("cloud-setup:fallingBackToLocal")}`);
        options.useCloud = false;
        return await this.executeCloudSetup(options);
      }
      throw error;
    }
  }
}

async function ccjkAll(options = {}) {
  const startTime = Date.now();
  await ensureI18nInitialized();
  if (options.help) {
    return displayHelp();
  }
  if (options.version) {
    return displayVersion();
  }
  if (options.lang) {
    i18n.changeLanguage(options.lang);
  }
  const logger = consola.withTag("ccjk:all");
  const isZh = i18n.language === "zh-CN";
  try {
    const result = {
      success: false,
      requestId: "",
      confidence: 0,
      installed: { skills: [], mcpServices: [], agents: [], hooks: [] },
      skipped: { skills: [], mcpServices: [], agents: [], hooks: [] },
      failed: { skills: [], mcpServices: [], agents: [], hooks: [] },
      duration: 0
    };
    if (options.json) {
      console.log(JSON.stringify({ status: "starting", options }));
    }
    if (!options.quiet && !options.json) {
      displayHeader();
    }
    if (!options.skipCloudCheck && options.useCloud !== false) {
      await checkCloudAvailability(options);
    }
    const orchestrator = new CloudSetupOrchestrator(options);
    const setupResult = await orchestrator.executeWithFallback(options);
    Object.assign(result, setupResult);
    if (options.json) {
      console.log(JSON.stringify({
        status: "completed",
        result: setupResult,
        duration: Date.now() - startTime
      }));
      return setupResult;
    }
    if (!options.quiet) {
      displayCompletion(setupResult);
    }
    return setupResult;
  } catch (error) {
    logger.error("Setup failed:", error);
    if (options.json) {
      console.log(JSON.stringify({
        status: "error",
        error: error.message,
        duration: Date.now() - startTime
      }));
    } else if (!options.quiet) {
      console.error(`
  ${a.red("\u2717")} ${isZh ? "\u8BBE\u7F6E\u5931\u8D25" : "Setup failed"}`);
      console.error(`    ${a.red(error.message)}`);
      if (error.code === "ENOTFOUND") {
        console.error(`
  ${a.yellow("\u2139")} ${isZh ? "\u4E91\u670D\u52A1\u548C\u672C\u5730\u670D\u52A1\u90FD\u4E0D\u53EF\u7528" : "Both cloud and local services are unavailable"}`);
        console.error(`    ${isZh ? "\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u6216\u7A0D\u540E\u518D\u8BD5" : "Please check your network connection or try again later"}`);
      }
    }
    throw error;
  }
}
function displayHeader() {
  console.log("");
  console.log(a.bold.cyan("\u2501".repeat(60)));
  console.log(a.bold.cyan(`  ${i18n.t("ccjk-all:title")}`));
  console.log(a.bold.cyan("\u2501".repeat(60)));
  console.log("");
}
async function checkCloudAvailability(options) {
  const logger = consola.withTag("cloud-check");
  i18n.language === "zh-CN";
  console.log(`  ${a.bold(i18n.t("ccjk-all:connectingToCloud"))}`);
  try {
    const client = createCompleteCloudClient({
      baseURL: options.cloudEndpoint || "https://api.ccjk.cloud"
    });
    const startTime = Date.now();
    const health = await client.healthCheck();
    const latency = Date.now() - startTime;
    console.log(`    ${a.green("\u2713")} ${i18n.t("ccjk-all:connected")} ${a.dim(`(${i18n.t("ccjk-all:latency")} ${latency}ms)`)}`);
    console.log(`    ${a.green("\u2713")} ${i18n.t("ccjk-all:cloudVersion")} ${a.dim(health.version || "unknown")}`);
  } catch (error) {
    logger.warn("Cloud service unavailable:", error);
    console.log(`    ${a.yellow("\u26A0")} ${i18n.t("ccjk-all:cloudUnavailable")}`);
    console.log(`    ${a.dim(i18n.t("ccjk-all:usingLocalMode"))}`);
    options.useCloud = false;
  }
}
function displayCompletion(result) {
  console.log("");
  console.log(a.green(`  ${i18n.t("ccjk-all:setupComplete")}`));
  const totalInstalled = result.installed.skills.length + result.installed.mcpServices.length + result.installed.agents.length + result.installed.hooks.length;
  console.log(`  ${i18n.t("ccjk-all:installedCount", { count: totalInstalled, duration: (result.duration / 1e3).toFixed(1) })}`);
  if (result.insights?.insights && result.insights.insights.length > 0) {
    console.log(`
  ${a.bold(i18n.t("ccjk-all:cloudFeedback"))}`);
    for (const insight of result.insights.insights) {
      console.log(`    ${a.cyan("\u2022")} ${insight}`);
    }
  }
  console.log(`
  ${a.bold(i18n.t("ccjk-all:nextSteps"))}`);
  console.log(`    ${a.dim("\u2022")} ${i18n.t("ccjk-all:startCoding")}`);
  console.log(`    ${a.dim("\u2022")} ${i18n.t("ccjk-all:viewRecommendations")}`);
  console.log(`    ${a.dim("\u2022")} ${i18n.t("ccjk-all:customizeSetup")}`);
  if (result.reportPath) {
    console.log(`
  ${a.dim(i18n.t("ccjk-all:reportGenerated", { path: result.reportPath }))}`);
  }
  console.log("");
}
function displayHelp() {
  i18n.language === "zh-CN";
  console.log("");
  console.log(a.bold.cyan("\u2501".repeat(60)));
  console.log(a.bold.cyan(`  ${i18n.t("ccjk-all:helpTitle")}`));
  console.log(a.bold.cyan("\u2501".repeat(60)));
  console.log("");
  console.log(a.bold(i18n.t("ccjk-all:usage")));
  console.log("  ccjk ccjk:all [options]");
  console.log("");
  console.log(a.bold(i18n.t("ccjk-all:options")));
  console.log("  --strategy <type>          Cloud strategy (cloud-smart, cloud-conservative, local-fallback)");
  console.log("  --use-cloud <bool>        Use cloud recommendations (default: true)");
  console.log("  --cloud-endpoint <url>   Cloud API endpoint");
  console.log("  --cache-strategy <type>  Cache strategy (aggressive, normal, disabled)");
  console.log("  --show-reasons           Show recommendation reasons");
  console.log("  --show-confidence        Show confidence scores");
  console.log("  --show-comparison        Show community comparison");
  console.log("  --submit-telemetry       Submit anonymous telemetry (default: true)");
  console.log("  --include-feedback       Include feedback after installation");
  console.log("  --generate-report        Generate detailed report");
  console.log("  --report-format <type>   Report format (markdown, json, html)");
  console.log("  --target-dir <path>      Target directory (default: current directory)");
  console.log("  --interactive            Interactive mode (default: true)");
  console.log("  --dry-run                Preview without installing");
  console.log("  --force                  Force installation");
  console.log("  --lang <lang>            Language (en, zh-CN)");
  console.log("  --json                   JSON output");
  console.log("  --quiet                  Quiet mode");
  console.log("  --verbose                Verbose output");
  console.log("  --help                   Show help");
  console.log("  --version                Show version");
  console.log("");
  console.log(a.bold(i18n.t("ccjk-all:examples")));
  console.log("  ccjk ccjk:all                    # Interactive cloud-powered setup");
  console.log("  ccjk ccjk:all --strategy cloud-smart  # Use cloud-smart strategy");
  console.log("  ccjk ccjk:all --use-cloud false  # Local mode only");
  console.log("  ccjk ccjk:all --show-reasons     # Show recommendation reasons");
  console.log("  ccjk ccjk:all --generate-report  # Generate detailed report");
  console.log("  ccjk ccjk:all --dry-run          # Preview without installing");
  console.log("");
  console.log(a.bold(i18n.t("ccjk-all:strategies")));
  console.log("  cloud-smart         Use cloud with intelligent fallback");
  console.log("  cloud-conservative  Prefer cloud but strict about errors");
  console.log("  local-fallback      Use local recommendations only");
  console.log("");
}
function displayVersion() {
  const pkg = require("../../package.json");
  console.log(`ccjk v${pkg.version}`);
}

export { ccjkAll };
