import { existsSync, mkdirSync } from 'node:fs';
import { appendFile, readFile } from 'node:fs/promises';
import { homedir } from 'node:os';
import { j as join } from './ccjk.bQ7Dh1g4.mjs';

function decideCapability(context) {
  const { input, conversationTurns, hasUncommittedChanges, recentFailures } = context;
  const lower = input.toLowerCase();
  if (lower.includes("\u89E3\u91CA") || lower.includes("\u4EC0\u4E48\u662F") || lower.includes("\u4E3A\u4EC0\u4E48") || lower.includes("\u5982\u4F55\u7406\u89E3")) {
    return {
      level: 0,
      reasoning: "\u7EAF\u6587\u672C\u63A8\u7406\u4EFB\u52A1",
      expectedSteps: 1,
      expectedDuration: 5,
      complexity: 1
    };
  }
  if (lower.startsWith("/") || lower.includes("commit") || lower.includes("review")) {
    return {
      level: 1,
      reasoning: "Skill\u5FEB\u6377\u6307\u4EE4",
      expectedSteps: 1,
      expectedDuration: 10,
      complexity: 2
    };
  }
  if ((lower.includes("\u4FEE\u6539") || lower.includes("fix") || lower.includes("\u66F4\u65B0")) && !lower.includes("\u6240\u6709") && !lower.includes("\u6279\u91CF")) {
    return {
      level: 2,
      reasoning: "\u5355\u6587\u4EF6\u4FEE\u6539",
      expectedSteps: 3,
      expectedDuration: 20,
      complexity: 3
    };
  }
  if (lower.includes("\u91CD\u6784") || lower.includes("\u6279\u91CF") || lower.includes("\u6240\u6709") || lower.includes("\u6DFB\u52A0") && lower.includes("\u529F\u80FD")) {
    return {
      level: 3,
      reasoning: "\u591A\u6587\u4EF6\u534F\u8C03\u64CD\u4F5C",
      expectedSteps: 8,
      expectedDuration: 60,
      complexity: 6
    };
  }
  if (lower.includes("\u5206\u6790\u6574\u4E2A") || lower.includes("\u5168\u5C40") || lower.includes("\u67B6\u6784") || lower.includes("\u8FC1\u79FB")) {
    return {
      level: 4,
      reasoning: "\u590D\u6742\u4EFB\u52A1\uFF0C\u5EFA\u8BAEsubagent",
      expectedSteps: 15,
      expectedDuration: 180,
      complexity: 8
    };
  }
  if (lower.includes("\u5B8C\u5168\u91CD\u5199") || lower.includes("\u4ECE\u96F6\u5F00\u59CB") || lower.includes("\u5927\u89C4\u6A21")) {
    return {
      level: 5,
      reasoning: "\u6781\u590D\u6742\u4EFB\u52A1\uFF0C\u5FC5\u987Bsubagent",
      expectedSteps: 30,
      expectedDuration: 600,
      complexity: 10
    };
  }
  const complexity = Math.min(
    10,
    3 + conversationTurns * 0.5 + recentFailures * 2 + (hasUncommittedChanges ? 1 : 0)
  );
  if (complexity >= 8) {
    return {
      level: 4,
      reasoning: "\u4E0A\u4E0B\u6587\u590D\u6742\u5EA6\u9AD8",
      expectedSteps: 12,
      expectedDuration: 120,
      complexity: Math.round(complexity)
    };
  }
  if (complexity >= 5) {
    return {
      level: 3,
      reasoning: "\u4E2D\u7B49\u590D\u6742\u5EA6\u4EFB\u52A1",
      expectedSteps: 6,
      expectedDuration: 45,
      complexity: Math.round(complexity)
    };
  }
  return {
    level: 2,
    reasoning: "\u6807\u51C6\u64CD\u4F5C",
    expectedSteps: 3,
    expectedDuration: 20,
    complexity: Math.round(complexity)
  };
}
function getCapabilityName(level) {
  const names = {
    0: "\u7EAF\u6587\u672C\u63A8\u7406",
    1: "Skill\u6267\u884C",
    2: "\u5355\u6587\u4EF6\u64CD\u4F5C",
    3: "\u591A\u6587\u4EF6\u534F\u8C03",
    4: "\u590D\u6742\u4EFB\u52A1",
    5: "\u6781\u590D\u6742\u4EFB\u52A1"
  };
  return names[level];
}

class BrainTelemetry {
  logPath;
  constructor(logPath) {
    const ccjkDir = join(homedir(), ".ccjk");
    if (!existsSync(ccjkDir)) {
      mkdirSync(ccjkDir, { recursive: true });
    }
    this.logPath = logPath ?? join(ccjkDir, "task-decision-log.jsonl");
  }
  /**
   * 记录任务执行
   */
  async logTask(log) {
    const line = JSON.stringify({
      ...log,
      timestamp: log.timestamp || (/* @__PURE__ */ new Date()).toISOString()
    });
    await appendFile(this.logPath, `${line}
`, "utf-8");
    const stats = await this.getStats();
    if (stats.totalTasks % 10 === 0) {
      await this.analyzeAndUpdate();
    }
  }
  /**
   * 读取所有日志
   */
  async readLogs() {
    if (!existsSync(this.logPath)) {
      return [];
    }
    const content = await readFile(this.logPath, "utf-8");
    const lines = content.trim().split("\n").filter(Boolean);
    return lines.map((line) => JSON.parse(line));
  }
  /**
   * 获取统计数据
   */
  async getStats() {
    const logs = await this.readLogs();
    if (logs.length === 0) {
      return {
        totalTasks: 0,
        byLevel: {},
        recentTrend: [],
        recommendations: []
      };
    }
    const byLevel = {};
    for (const log of logs) {
      if (!byLevel[log.level]) {
        byLevel[log.level] = [];
      }
      byLevel[log.level].push(log);
    }
    const levelStats = {};
    for (const [level, levelLogs] of Object.entries(byLevel)) {
      const successCount = levelLogs.filter((l) => l.success).length;
      const totalDuration = levelLogs.reduce((sum, l) => sum + l.duration, 0);
      const totalScore = levelLogs.reduce((sum, l) => sum + l.effectScore, 0);
      levelStats[Number(level)] = {
        count: levelLogs.length,
        successRate: successCount / levelLogs.length,
        avgDuration: totalDuration / levelLogs.length,
        avgEffectScore: totalScore / levelLogs.length
      };
    }
    const thirtyDaysAgo = /* @__PURE__ */ new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
    const recentLogs = logs.filter(
      (log) => new Date(log.timestamp) >= thirtyDaysAgo
    );
    const dailyStats = /* @__PURE__ */ new Map();
    for (const log of recentLogs) {
      const date = log.timestamp.split("T")[0];
      const stats = dailyStats.get(date) ?? { count: 0, success: 0 };
      stats.count++;
      if (log.success)
        stats.success++;
      dailyStats.set(date, stats);
    }
    const recentTrend = Array.from(dailyStats.entries()).map(([date, stats]) => ({
      date,
      count: stats.count,
      successRate: stats.success / stats.count
    })).sort((a, b) => a.date.localeCompare(b.date));
    const recommendations = this.generateRecommendations(levelStats);
    return {
      totalTasks: logs.length,
      byLevel: levelStats,
      recentTrend,
      recommendations
    };
  }
  /**
   * 生成优化建议
   */
  generateRecommendations(levelStats) {
    const recommendations = [];
    for (const [level, stats] of Object.entries(levelStats)) {
      const levelNum = Number(level);
      if (stats.successRate < 0.8) {
        recommendations.push(
          `Level ${levelNum} \u6210\u529F\u7387\u504F\u4F4E (${(stats.successRate * 100).toFixed(1)}%)\uFF0C\u8003\u8651\u964D\u7EA7\u5230\u66F4\u7B80\u5355\u7684\u5C42\u7EA7`
        );
      }
      if (stats.avgEffectScore < 7) {
        recommendations.push(
          `Level ${levelNum} \u6548\u679C\u8BC4\u5206\u504F\u4F4E (${stats.avgEffectScore.toFixed(1)}/10)\uFF0C\u9700\u8981\u4F18\u5316\u6267\u884C\u7B56\u7565`
        );
      }
      if (levelNum <= 2 && stats.avgDuration > 30) {
        recommendations.push(
          `Level ${levelNum} \u5E73\u5747\u8017\u65F6\u8FC7\u957F (${stats.avgDuration.toFixed(1)}s)\uFF0C\u8003\u8651\u4F18\u5316\u6216\u5347\u7EA7`
        );
      }
    }
    return recommendations;
  }
  /**
   * 分析并更新方法论
   */
  async analyzeAndUpdate() {
    const stats = await this.getStats();
    if (stats.recommendations.length > 0) {
      console.log("\n\u{1F4CA} Brain Telemetry Analysis:");
      for (const rec of stats.recommendations) {
        console.log(`  \u{1F4A1} ${rec}`);
      }
      console.log();
    }
  }
  /**
   * 清空日志
   */
  async clear() {
    if (existsSync(this.logPath)) {
      await appendFile(this.logPath, "", "utf-8");
    }
  }
}
let globalTelemetry = null;
function getTelemetry() {
  if (!globalTelemetry) {
    globalTelemetry = new BrainTelemetry();
  }
  return globalTelemetry;
}

class SmartRouter {
  config;
  recentFailures = 0;
  constructor(config = {}) {
    this.config = {
      capabilityPreference: config.capabilityPreference ?? 2,
      autoSubagentThreshold: config.autoSubagentThreshold ?? 7,
      maxParallelAgents: config.maxParallelAgents ?? 3,
      enableTelemetry: config.enableTelemetry ?? true,
      showReasoning: config.showReasoning ?? true
    };
  }
  /**
   * 路由任务到合适的能力层级
   */
  async route(input, context = {}) {
    const fullContext = {
      input,
      conversationTurns: context.conversationTurns ?? 0,
      cwd: context.cwd ?? process.cwd(),
      hasUncommittedChanges: context.hasUncommittedChanges ?? false,
      recentFailures: this.recentFailures
    };
    const decision = decideCapability(fullContext);
    const adjustedDecision = this.applyPreference(decision);
    const executionAdvice = this.generateAdvice(adjustedDecision);
    if (this.config.showReasoning) {
      console.log(`
[Brain Router] \u51B3\u7B56: ${getCapabilityName(adjustedDecision.level)}`);
      console.log(`  \u7406\u7531: ${adjustedDecision.reasoning}`);
      console.log(`  \u9884\u671F: ${adjustedDecision.expectedSteps}\u6B65 / ${adjustedDecision.expectedDuration}s`);
      console.log(`  \u590D\u6742\u5EA6: ${adjustedDecision.complexity}/10
`);
    }
    return {
      decision: adjustedDecision,
      shouldExecute: this.shouldExecute(adjustedDecision),
      executionAdvice
    };
  }
  /**
   * 应用用户偏好调整决策
   */
  applyPreference(decision) {
    const { capabilityPreference, autoSubagentThreshold } = this.config;
    if (capabilityPreference <= 2 && decision.level >= 3) {
      if (decision.complexity < autoSubagentThreshold) {
        return {
          ...decision,
          level: 2,
          // 降级到主Agent
          reasoning: `${decision.reasoning} (\u7528\u6237\u504F\u597D\u7B80\u5355\uFF0C\u964D\u7EA7\u5230\u4E3BAgent)`
        };
      }
    }
    if (capabilityPreference >= 4 && decision.level === 2) {
      if (decision.complexity >= 5) {
        return {
          ...decision,
          level: 3,
          // 升级到Subagent
          reasoning: `${decision.reasoning} (\u7528\u6237\u504F\u597D\u590D\u6742\uFF0C\u5347\u7EA7\u5230Subagent)`
        };
      }
    }
    return decision;
  }
  /**
   * 判断是否应该执行
   */
  shouldExecute(decision) {
    if (decision.level <= 1)
      return true;
    if (decision.level === 2)
      return true;
    if (decision.level === 3) {
      return decision.complexity >= this.config.autoSubagentThreshold;
    }
    return false;
  }
  /**
   * 生成执行建议
   */
  generateAdvice(decision) {
    switch (decision.level) {
      case 0:
        return "\u76F4\u63A5\u56DE\u7B54\uFF0C\u65E0\u9700\u5DE5\u5177\u8C03\u7528";
      case 1:
        return "\u4F7F\u7528Skill\u6267\u884C\uFF0C\u5355\u6B65\u5B8C\u6210";
      case 2:
        return "\u4E3BAgent\u5904\u7406\uFF0C\u9884\u8BA13-5\u6B65\u5B8C\u6210";
      case 3:
        return `\u542F\u52A8Subagent\uFF0C\u9884\u8BA1${decision.expectedSteps}\u6B65\u5B8C\u6210`;
      case 4:
        return "\u9700\u8981\u591AAgent\u534F\u4F5C\uFF0C\u5EFA\u8BAE\u7528\u6237\u786E\u8BA4";
      case 5:
        return "\u9700\u8981\u957F\u5BFFSession\uFF0C\u5EFA\u8BAE\u7528\u6237\u786E\u8BA4";
      default:
        return "\u672A\u77E5\u5C42\u7EA7";
    }
  }
  /**
   * 记录任务执行结果
   */
  async recordExecution(decision, result) {
    if (!this.config.enableTelemetry)
      return;
    const telemetry = getTelemetry();
    const log = {
      timestamp: (/* @__PURE__ */ new Date()).toISOString(),
      task: decision.reasoning,
      level: decision.level,
      actualSteps: result.actualSteps,
      duration: result.duration,
      success: result.success,
      effectScore: result.effectScore,
      recommendation: this.generateRecommendation(decision, result)
    };
    await telemetry.logTask(log);
    if (!result.success) {
      this.recentFailures++;
    } else {
      this.recentFailures = 0;
    }
  }
  /**
   * 生成下次建议
   */
  generateRecommendation(decision, result) {
    if (!result.success) {
      return `\u5931\u8D25\uFF0C\u4E0B\u6B21\u8003\u8651\u5347\u7EA7\u5230Level ${decision.level + 1}`;
    }
    if (result.effectScore < 7) {
      return `\u6548\u679C\u4E00\u822C\uFF0C\u4E0B\u6B21\u8003\u8651\u8C03\u6574\u7B56\u7565`;
    }
    return `\u6548\u679C\u826F\u597D\uFF0C\u7EE7\u7EED\u4F7F\u7528Level ${decision.level}`;
  }
  /**
   * 获取配置
   */
  getConfig() {
    return { ...this.config };
  }
  /**
   * 更新配置
   */
  updateConfig(config) {
    this.config = { ...this.config, ...config };
  }
  /**
   * 重置失败计数
   */
  resetFailures() {
    this.recentFailures = 0;
  }
}
let globalRouter = null;
function getSmartRouter() {
  if (!globalRouter) {
    globalRouter = new SmartRouter();
  }
  return globalRouter;
}

export { getSmartRouter as a, getCapabilityName as b, getTelemetry as g };
