import a from './index5.mjs';
import { i18n } from './index2.mjs';
import { displayBannerWithInfo } from './banner.mjs';
import process__default from 'node:process';
import { n as nanoid } from '../shared/ccjk.BoApaI4j.mjs';
import '../shared/ccjk.BAGoDD49.mjs';
import 'node:fs';
import 'node:url';
import '../shared/ccjk.bQ7Dh1g4.mjs';
import '../shared/ccjk.gDEDGD_t.mjs';
import 'node:crypto';

const DEFAULT_STORAGE_CONFIG = {
  maxRecords: 1e4,
  retentionPeriod: 7 * 24 * 60 * 60 * 1e3,
  // 7 days
  enablePersistence: false,
  compressOldData: true
};
class MetricsCollector {
  commands = /* @__PURE__ */ new Map();
  commandHistory = [];
  apiCalls = /* @__PURE__ */ new Map();
  apiHistory = [];
  cacheOperations = [];
  errors = [];
  agentTasks = /* @__PURE__ */ new Map();
  agentHistory = [];
  memorySnapshots = [];
  eventListeners = /* @__PURE__ */ new Map();
  thresholds = [];
  config;
  startTime;
  constructor(config = {}) {
    this.config = { ...DEFAULT_STORAGE_CONFIG, ...config };
    this.startTime = Date.now();
  }
  // ==========================================================================
  // Command Metrics
  // ==========================================================================
  /**
   * Start tracking a command execution
   */
  startCommand(command, args = []) {
    const id = nanoid();
    const execution = {
      id,
      command,
      args,
      startTime: Date.now(),
      status: "running"
    };
    this.commands.set(id, execution);
    this.emit("command:start", execution);
    return id;
  }
  /**
   * End tracking a command execution
   */
  endCommand(id, status, error) {
    const execution = this.commands.get(id);
    if (!execution)
      return;
    execution.endTime = Date.now();
    execution.duration = execution.endTime - execution.startTime;
    execution.status = status;
    execution.error = error;
    execution.memoryUsed = process.memoryUsage().heapUsed;
    this.commandHistory.push(execution);
    this.commands.delete(id);
    this.trimHistory(this.commandHistory);
    this.emit("command:end", execution);
    this.checkThresholds("command.duration", execution.duration);
  }
  /**
   * Get command statistics
   */
  getCommandStats() {
    const statsMap = /* @__PURE__ */ new Map();
    for (const exec of this.commandHistory) {
      let stats = statsMap.get(exec.command);
      if (!stats) {
        stats = {
          command: exec.command,
          totalExecutions: 0,
          successCount: 0,
          failureCount: 0,
          avgDuration: 0,
          minDuration: Infinity,
          maxDuration: 0,
          p95Duration: 0
        };
        statsMap.set(exec.command, stats);
      }
      stats.totalExecutions++;
      if (exec.status === "success")
        stats.successCount++;
      else if (exec.status === "failed" || exec.status === "timeout")
        stats.failureCount++;
      if (exec.duration !== void 0) {
        stats.minDuration = Math.min(stats.minDuration, exec.duration);
        stats.maxDuration = Math.max(stats.maxDuration, exec.duration);
      }
      stats.lastExecution = exec.endTime || exec.startTime;
    }
    for (const [command, stats] of statsMap) {
      const durations = this.commandHistory.filter((e) => e.command === command && e.duration !== void 0).map((e) => e.duration).sort((a, b) => a - b);
      if (durations.length > 0) {
        stats.avgDuration = durations.reduce((a, b) => a + b, 0) / durations.length;
        stats.p95Duration = this.calculatePercentile(durations, 95);
      }
      if (stats.minDuration === Infinity)
        stats.minDuration = 0;
    }
    return Array.from(statsMap.values());
  }
  // ==========================================================================
  // API Call Metrics
  // ==========================================================================
  /**
   * Start tracking an API call
   */
  startApiCall(provider, endpoint, method = "POST") {
    const id = nanoid();
    const record = {
      id,
      provider,
      endpoint,
      method,
      startTime: Date.now(),
      status: "pending"
    };
    this.apiCalls.set(id, record);
    this.emit("api:start", record);
    return id;
  }
  /**
   * End tracking an API call
   */
  endApiCall(id, status, options = {}) {
    const record = this.apiCalls.get(id);
    if (!record)
      return;
    record.endTime = Date.now();
    record.latency = record.endTime - record.startTime;
    record.status = status;
    record.statusCode = options.statusCode;
    record.error = options.error;
    record.requestSize = options.requestSize;
    record.responseSize = options.responseSize;
    record.tokensUsed = options.tokensUsed;
    record.cached = options.cached;
    this.apiHistory.push(record);
    this.apiCalls.delete(id);
    this.trimHistory(this.apiHistory);
    this.emit("api:end", record);
    this.checkThresholds("api.latency", record.latency);
  }
  /**
   * Get API statistics by provider
   */
  getApiStats() {
    const statsMap = /* @__PURE__ */ new Map();
    for (const call of this.apiHistory) {
      let stats = statsMap.get(call.provider);
      if (!stats) {
        stats = {
          provider: call.provider,
          totalCalls: 0,
          successCount: 0,
          failureCount: 0,
          avgLatency: 0,
          minLatency: Infinity,
          maxLatency: 0,
          p95Latency: 0,
          totalTokens: 0,
          cacheHits: 0,
          cacheMisses: 0,
          errorRate: 0
        };
        statsMap.set(call.provider, stats);
      }
      stats.totalCalls++;
      if (call.status === "success")
        stats.successCount++;
      else stats.failureCount++;
      if (call.latency !== void 0) {
        stats.minLatency = Math.min(stats.minLatency, call.latency);
        stats.maxLatency = Math.max(stats.maxLatency, call.latency);
      }
      if (call.tokensUsed)
        stats.totalTokens += call.tokensUsed;
      if (call.cached)
        stats.cacheHits++;
      else stats.cacheMisses++;
    }
    for (const [provider, stats] of statsMap) {
      const latencies = this.apiHistory.filter((c) => c.provider === provider && c.latency !== void 0).map((c) => c.latency).sort((a, b) => a - b);
      if (latencies.length > 0) {
        stats.avgLatency = latencies.reduce((a, b) => a + b, 0) / latencies.length;
        stats.p95Latency = this.calculatePercentile(latencies, 95);
      }
      if (stats.minLatency === Infinity)
        stats.minLatency = 0;
      stats.errorRate = stats.totalCalls > 0 ? stats.failureCount / stats.totalCalls : 0;
    }
    return Array.from(statsMap.values());
  }
  // ==========================================================================
  // Cache Metrics
  // ==========================================================================
  /**
   * Record a cache operation
   */
  recordCacheOperation(operation, key, hit, latency, size) {
    const record = {
      timestamp: Date.now(),
      operation,
      key,
      hit,
      latency,
      size
    };
    this.cacheOperations.push(record);
    this.trimHistory(this.cacheOperations);
    this.emit("cache:operation", record);
  }
  /**
   * Get cache statistics
   */
  getCacheStats() {
    const getOps = this.cacheOperations.filter((op) => op.operation === "get");
    const hits = getOps.filter((op) => op.hit).length;
    const misses = getOps.filter((op) => !op.hit).length;
    const totalSize = this.cacheOperations.filter((op) => op.size !== void 0).reduce((sum, op) => sum + (op.size || 0), 0);
    const latencies = this.cacheOperations.map((op) => op.latency);
    const avgLatency = latencies.length > 0 ? latencies.reduce((a, b) => a + b, 0) / latencies.length : 0;
    return {
      totalOperations: this.cacheOperations.length,
      hits,
      misses,
      hitRate: getOps.length > 0 ? hits / getOps.length : 0,
      avgLatency,
      totalSize,
      itemCount: new Set(this.cacheOperations.map((op) => op.key)).size,
      evictions: this.cacheOperations.filter((op) => op.operation === "delete").length
    };
  }
  // ==========================================================================
  // Error Metrics
  // ==========================================================================
  /**
   * Record an error
   */
  recordError(type, message, options = {}) {
    const id = nanoid();
    const record = {
      id,
      timestamp: Date.now(),
      type,
      message,
      stack: options.stack,
      context: options.context,
      severity: options.severity || "medium",
      resolved: false
    };
    this.errors.push(record);
    this.trimHistory(this.errors);
    this.emit("error:recorded", record);
    this.checkThresholds("error.count", this.errors.length);
    return id;
  }
  /**
   * Mark an error as resolved
   */
  resolveError(id) {
    const error = this.errors.find((e) => e.id === id);
    if (error) {
      error.resolved = true;
    }
  }
  /**
   * Get error statistics
   */
  getErrorStats() {
    const errorsByType = {};
    const errorsBySeverity = { low: 0, medium: 0, high: 0, critical: 0 };
    for (const error of this.errors) {
      errorsByType[error.type] = (errorsByType[error.type] || 0) + 1;
      errorsBySeverity[error.severity]++;
    }
    const recentErrors = this.errors.slice(-10).reverse();
    const oneHourAgo = Date.now() - 60 * 60 * 1e3;
    const recentErrorCount = this.errors.filter((e) => e.timestamp > oneHourAgo).length;
    const errorRate = recentErrorCount / 60;
    return {
      totalErrors: this.errors.length,
      errorsByType,
      errorsBySeverity,
      errorRate,
      recentErrors
    };
  }
  // ==========================================================================
  // Agent Task Metrics
  // ==========================================================================
  /**
   * Start tracking an agent task
   */
  startAgentTask(agentId, agentName, taskType) {
    const id = nanoid();
    const record = {
      id,
      agentId,
      agentName,
      taskType,
      startTime: Date.now(),
      status: "running"
    };
    this.agentTasks.set(id, record);
    this.emit("agent:task:start", record);
    return id;
  }
  /**
   * End tracking an agent task
   */
  endAgentTask(id, status, options = {}) {
    const record = this.agentTasks.get(id);
    if (!record)
      return;
    record.endTime = Date.now();
    record.duration = record.endTime - record.startTime;
    record.status = status;
    record.tokensUsed = options.tokensUsed;
    record.error = options.error;
    record.metadata = options.metadata;
    this.agentHistory.push(record);
    this.agentTasks.delete(id);
    this.trimHistory(this.agentHistory);
    this.emit("agent:task:end", record);
  }
  /**
   * Get agent statistics
   */
  getAgentStats() {
    const statsMap = /* @__PURE__ */ new Map();
    for (const task of this.agentHistory) {
      let stats = statsMap.get(task.agentId);
      if (!stats) {
        stats = {
          agentId: task.agentId,
          agentName: task.agentName,
          totalTasks: 0,
          successCount: 0,
          failureCount: 0,
          avgDuration: 0,
          totalTokens: 0,
          successRate: 0
        };
        statsMap.set(task.agentId, stats);
      }
      stats.totalTasks++;
      if (task.status === "success")
        stats.successCount++;
      else if (task.status === "failed")
        stats.failureCount++;
      if (task.tokensUsed)
        stats.totalTokens += task.tokensUsed;
      stats.lastActive = task.endTime || task.startTime;
    }
    for (const [agentId, stats] of statsMap) {
      const durations = this.agentHistory.filter((t) => t.agentId === agentId && t.duration !== void 0).map((t) => t.duration);
      if (durations.length > 0) {
        stats.avgDuration = durations.reduce((a, b) => a + b, 0) / durations.length;
      }
      stats.successRate = stats.totalTasks > 0 ? stats.successCount / stats.totalTasks : 0;
    }
    return Array.from(statsMap.values());
  }
  // ==========================================================================
  // Memory Metrics
  // ==========================================================================
  /**
   * Take a memory snapshot
   */
  takeMemorySnapshot() {
    const mem = process.memoryUsage();
    const snapshot = {
      timestamp: Date.now(),
      heapUsed: mem.heapUsed,
      heapTotal: mem.heapTotal,
      external: mem.external,
      arrayBuffers: mem.arrayBuffers,
      rss: mem.rss,
      heapUsedPercent: mem.heapUsed / mem.heapTotal
    };
    this.memorySnapshots.push(snapshot);
    this.trimHistory(this.memorySnapshots);
    this.emit("memory:snapshot", snapshot);
    this.checkThresholds("memory.heapUsedPercent", snapshot.heapUsedPercent);
    return snapshot;
  }
  /**
   * Get memory statistics
   */
  getMemoryStats() {
    const current = this.takeMemorySnapshot();
    if (this.memorySnapshots.length === 0) {
      return {
        current,
        peak: current,
        average: {
          heapUsed: current.heapUsed,
          heapTotal: current.heapTotal,
          rss: current.rss
        },
        trend: "stable"
      };
    }
    const peak = this.memorySnapshots.reduce(
      (max, snap) => snap.heapUsed > max.heapUsed ? snap : max
    );
    const avgHeapUsed = this.memorySnapshots.reduce((sum, s) => sum + s.heapUsed, 0) / this.memorySnapshots.length;
    const avgHeapTotal = this.memorySnapshots.reduce((sum, s) => sum + s.heapTotal, 0) / this.memorySnapshots.length;
    const avgRss = this.memorySnapshots.reduce((sum, s) => sum + s.rss, 0) / this.memorySnapshots.length;
    let trend = "stable";
    if (this.memorySnapshots.length >= 5) {
      const recent = this.memorySnapshots.slice(-5);
      const first = recent[0].heapUsed;
      const last = recent[recent.length - 1].heapUsed;
      const change = (last - first) / first;
      if (change > 0.1)
        trend = "increasing";
      else if (change < -0.1)
        trend = "decreasing";
    }
    return {
      current,
      peak,
      average: {
        heapUsed: avgHeapUsed,
        heapTotal: avgHeapTotal,
        rss: avgRss
      },
      trend
    };
  }
  // ==========================================================================
  // Event System
  // ==========================================================================
  /**
   * Subscribe to metric events
   */
  on(type, listener) {
    if (!this.eventListeners.has(type)) {
      this.eventListeners.set(type, /* @__PURE__ */ new Set());
    }
    this.eventListeners.get(type).add(listener);
    return () => {
      this.eventListeners.get(type)?.delete(listener);
    };
  }
  /**
   * Emit a metric event
   */
  emit(type, data) {
    const event = { type, timestamp: Date.now(), data };
    this.eventListeners.get(type)?.forEach((listener) => {
      try {
        listener(event);
      } catch {
      }
    });
  }
  // ==========================================================================
  // Threshold System
  // ==========================================================================
  /**
   * Add a threshold configuration
   */
  addThreshold(config) {
    this.thresholds.push(config);
  }
  /**
   * Remove a threshold configuration
   */
  removeThreshold(metric) {
    this.thresholds = this.thresholds.filter((t) => t.metric !== metric);
  }
  /**
   * Check thresholds and emit alerts
   */
  checkThresholds(metric, value) {
    for (const threshold of this.thresholds) {
      if (threshold.metric !== metric)
        continue;
      let exceeded = false;
      let level = "warning";
      const checkValue = (limit, comparison) => {
        switch (comparison) {
          case "gt":
            return value > limit;
          case "lt":
            return value < limit;
          case "gte":
            return value >= limit;
          case "lte":
            return value <= limit;
          case "eq":
            return value === limit;
          default:
            return false;
        }
      };
      if (checkValue(threshold.critical, threshold.comparison)) {
        exceeded = true;
        level = "critical";
      } else if (checkValue(threshold.warning, threshold.comparison)) {
        exceeded = true;
        level = "warning";
      }
      if (exceeded) {
        const alert = {
          threshold,
          currentValue: value,
          level,
          timestamp: Date.now(),
          message: `${metric} ${level}: ${value} (threshold: ${level === "critical" ? threshold.critical : threshold.warning})`
        };
        this.emit("threshold:exceeded", alert);
      }
    }
  }
  // ==========================================================================
  // Utility Methods
  // ==========================================================================
  /**
   * Calculate percentile from sorted array
   */
  calculatePercentile(sortedValues, percentile) {
    if (sortedValues.length === 0)
      return 0;
    const index = Math.ceil(percentile / 100 * sortedValues.length) - 1;
    return sortedValues[Math.max(0, index)];
  }
  /**
   * Trim history arrays to max records
   */
  trimHistory(array) {
    const cutoff = Date.now() - this.config.retentionPeriod;
    while (array.length > 0) {
      const timestamp = array[0].timestamp || array[0].startTime || 0;
      if (timestamp < cutoff) {
        array.shift();
      } else {
        break;
      }
    }
    while (array.length > this.config.maxRecords) {
      array.shift();
    }
  }
  /**
   * Calculate aggregated statistics
   */
  aggregate(values) {
    if (values.length === 0) {
      return {
        min: 0,
        max: 0,
        avg: 0,
        median: 0,
        p95: 0,
        p99: 0,
        sum: 0,
        count: 0,
        stdDev: 0
      };
    }
    const sorted = [...values].sort((a, b) => a - b);
    const sum = values.reduce((a, b) => a + b, 0);
    const avg = sum / values.length;
    const squaredDiffs = values.map((v) => (v - avg) ** 2);
    const avgSquaredDiff = squaredDiffs.reduce((a, b) => a + b, 0) / values.length;
    const stdDev = Math.sqrt(avgSquaredDiff);
    return {
      min: sorted[0],
      max: sorted[sorted.length - 1],
      avg,
      median: this.calculatePercentile(sorted, 50),
      p95: this.calculatePercentile(sorted, 95),
      p99: this.calculatePercentile(sorted, 99),
      sum,
      count: values.length,
      stdDev
    };
  }
  /**
   * Get uptime in milliseconds
   */
  getUptime() {
    return Date.now() - this.startTime;
  }
  /**
   * Export all metrics data
   */
  exportData() {
    return {
      version: "1.0.0",
      savedAt: Date.now(),
      commands: this.commandHistory,
      apiCalls: this.apiHistory,
      cacheOps: this.cacheOperations,
      errors: this.errors,
      agentTasks: this.agentHistory,
      memorySnapshots: this.memorySnapshots
    };
  }
  /**
   * Import metrics data
   */
  importData(data) {
    this.commandHistory = data.commands || [];
    this.apiHistory = data.apiCalls || [];
    this.cacheOperations = data.cacheOps || [];
    this.errors = data.errors || [];
    this.agentHistory = data.agentTasks || [];
    this.memorySnapshots = data.memorySnapshots || [];
  }
  /**
   * Clear all metrics
   */
  clear() {
    this.commands.clear();
    this.commandHistory = [];
    this.apiCalls.clear();
    this.apiHistory = [];
    this.cacheOperations = [];
    this.errors = [];
    this.agentTasks.clear();
    this.agentHistory = [];
    this.memorySnapshots = [];
  }
}
let globalCollector;
function getMetricsCollector(config) {
  if (!globalCollector) {
    globalCollector = new MetricsCollector(config);
  }
  return globalCollector;
}

const DEFAULT_CONFIG = {
  refreshInterval: 2e3,
  showCommands: true,
  showMemory: true,
  showApi: true,
  showCache: true,
  showErrors: true,
  showAgents: true,
  chartWidth: 40,
  chartHeight: 8,
  colorScheme: "default"
};
function generateBarChart(data, options = {}) {
  const { width = 30, showValues = true } = options;
  const maxValue = options.maxValue || Math.max(...data.map((d) => d.value), 1);
  const maxLabelLength = Math.max(...data.map((d) => d.label.length), 10);
  const lines = [];
  for (const item of data) {
    const barLength = Math.round(item.value / maxValue * width);
    const bar = a.green("\u2588".repeat(barLength)) + a.dim("\u2591".repeat(width - barLength));
    const label = item.label.padEnd(maxLabelLength);
    const value = showValues ? ` ${item.value.toFixed(0)}` : "";
    lines.push(`  ${a.cyan(label)} ${bar}${a.yellow(value)}`);
  }
  return lines;
}
function generateSparkline(values, width = 20) {
  if (values.length === 0)
    return a.dim("\u2500".repeat(width));
  const chars = ["\u2581", "\u2582", "\u2583", "\u2584", "\u2585", "\u2586", "\u2587", "\u2588"];
  const min = Math.min(...values);
  const max = Math.max(...values);
  const range = max - min || 1;
  const step = Math.max(1, Math.floor(values.length / width));
  const sampled = values.filter((_, i) => i % step === 0).slice(-width);
  return sampled.map((v) => {
    const normalized = (v - min) / range;
    const index = Math.min(Math.floor(normalized * chars.length), chars.length - 1);
    return a.green(chars[index]);
  }).join("");
}
function generateProgressBar(value, max, width = 20, options = {}) {
  const { showPercent = true, colorThresholds } = options;
  const percent = Math.min(value / max, 1);
  const filled = Math.round(percent * width);
  const empty = width - filled;
  let color = a.green;
  if (colorThresholds) {
    if (percent >= colorThresholds.critical)
      color = a.red;
    else if (percent >= colorThresholds.warning)
      color = a.yellow;
  }
  const bar = color("\u2588".repeat(filled)) + a.dim("\u2591".repeat(empty));
  const percentStr = showPercent ? ` ${(percent * 100).toFixed(1)}%` : "";
  return `[${bar}]${a.yellow(percentStr)}`;
}
function formatDuration(ms) {
  if (ms < 1e3)
    return `${ms.toFixed(0)}ms`;
  if (ms < 6e4)
    return `${(ms / 1e3).toFixed(1)}s`;
  if (ms < 36e5)
    return `${(ms / 6e4).toFixed(1)}m`;
  return `${(ms / 36e5).toFixed(1)}h`;
}
function formatBytes(bytes) {
  if (bytes < 1024)
    return `${bytes}B`;
  if (bytes < 1024 * 1024)
    return `${(bytes / 1024).toFixed(1)}KB`;
  if (bytes < 1024 * 1024 * 1024)
    return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
  return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)}GB`;
}
function formatUptime(ms) {
  const seconds = Math.floor(ms / 1e3);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);
  if (days > 0)
    return `${days}d ${hours % 24}h ${minutes % 60}m`;
  if (hours > 0)
    return `${hours}h ${minutes % 60}m ${seconds % 60}s`;
  if (minutes > 0)
    return `${minutes}m ${seconds % 60}s`;
  return `${seconds}s`;
}
function getHealthColor(status) {
  switch (status) {
    case "healthy":
      return a.green;
    case "degraded":
      return a.yellow;
    case "unhealthy":
      return a.red;
    case "critical":
      return a.red.bold;
    default:
      return a.gray;
  }
}
function getHealthIcon(status) {
  switch (status) {
    case "healthy":
      return a.green("\u25CF");
    case "degraded":
      return a.yellow("\u25D0");
    case "unhealthy":
      return a.red("\u25CB");
    case "critical":
      return a.red.bold("\u2716");
    default:
      return a.gray("?");
  }
}
class DashboardRenderer {
  config;
  collector;
  memoryHistory = [];
  apiLatencyHistory = [];
  constructor(config, collector) {
    this.config = config;
    this.collector = collector;
  }
  /**
   * Render the complete dashboard
   */
  render() {
    const lines = [];
    lines.push(...this.renderHeader());
    lines.push("");
    lines.push(...this.renderSystemOverview());
    lines.push("");
    const leftColumn = [];
    const rightColumn = [];
    if (this.config.showMemory) {
      leftColumn.push(...this.renderMemorySection());
      leftColumn.push("");
    }
    if (this.config.showApi) {
      leftColumn.push(...this.renderApiSection());
      leftColumn.push("");
    }
    if (this.config.showCommands) {
      rightColumn.push(...this.renderCommandsSection());
      rightColumn.push("");
    }
    if (this.config.showCache) {
      rightColumn.push(...this.renderCacheSection());
      rightColumn.push("");
    }
    const maxLines = Math.max(leftColumn.length, rightColumn.length);
    for (let i = 0; i < maxLines; i++) {
      const left = (leftColumn[i] || "").padEnd(50);
      const right = rightColumn[i] || "";
      lines.push(`${left}  ${right}`);
    }
    if (this.config.showErrors) {
      lines.push("");
      lines.push(...this.renderErrorsSection());
    }
    if (this.config.showAgents) {
      lines.push("");
      lines.push(...this.renderAgentsSection());
    }
    lines.push("");
    lines.push(...this.renderFooter());
    return lines.join("\n");
  }
  /**
   * Render dashboard header
   */
  renderHeader() {
    const title = a.bold.cyan("CCJK Performance Monitor");
    const time = a.dim((/* @__PURE__ */ new Date()).toLocaleString());
    const separator = a.dim("\u2550".repeat(80));
    return [
      separator,
      `  ${title}${" ".repeat(80 - 30 - time.length)}${time}`,
      separator
    ];
  }
  /**
   * Render system overview section
   */
  renderSystemOverview() {
    const memStats = this.collector.getMemoryStats();
    const uptime = this.collector.getUptime();
    const errorStats = this.collector.getErrorStats();
    let health = "healthy";
    if (errorStats.errorsBySeverity.critical > 0)
      health = "critical";
    else if (errorStats.errorsBySeverity.high > 0)
      health = "unhealthy";
    else if (memStats.current.heapUsedPercent > 0.9)
      health = "degraded";
    const healthColor = getHealthColor(health);
    const healthIcon = getHealthIcon(health);
    return [
      a.bold.white("  System Overview"),
      a.dim(`  ${"\u2500".repeat(40)}`),
      `  ${healthIcon} Status: ${healthColor(health.toUpperCase())}`,
      `  ${a.cyan("\u23F1")}  Uptime: ${a.yellow(formatUptime(uptime))}`,
      `  ${a.cyan("\u{1F4CA}")} Memory: ${formatBytes(memStats.current.heapUsed)} / ${formatBytes(memStats.current.heapTotal)}`,
      `  ${a.cyan("\u26A0")}  Errors: ${errorStats.totalErrors > 0 ? a.red(errorStats.totalErrors.toString()) : a.green("0")}`
    ];
  }
  /**
   * Render memory section
   */
  renderMemorySection() {
    const stats = this.collector.getMemoryStats();
    this.memoryHistory.push(stats.current.heapUsedPercent * 100);
    if (this.memoryHistory.length > 60)
      this.memoryHistory.shift();
    const lines = [
      a.bold.white("  Memory Usage"),
      a.dim(`  ${"\u2500".repeat(40)}`)
    ];
    const memBar = generateProgressBar(
      stats.current.heapUsed,
      stats.current.heapTotal,
      30,
      { colorThresholds: { warning: 0.7, critical: 0.9 } }
    );
    lines.push(`  Heap: ${memBar}`);
    lines.push(`  ${a.dim("Used:")} ${a.yellow(formatBytes(stats.current.heapUsed))}`);
    lines.push(`  ${a.dim("Total:")} ${a.yellow(formatBytes(stats.current.heapTotal))}`);
    lines.push(`  ${a.dim("RSS:")} ${a.yellow(formatBytes(stats.current.rss))}`);
    const trendIcon = stats.trend === "increasing" ? a.red("\u2191") : stats.trend === "decreasing" ? a.green("\u2193") : a.gray("\u2192");
    lines.push(`  ${a.dim("Trend:")} ${trendIcon} ${stats.trend}`);
    lines.push(`  ${a.dim("History:")} ${generateSparkline(this.memoryHistory, 30)}`);
    return lines;
  }
  /**
   * Render API section
   */
  renderApiSection() {
    const stats = this.collector.getApiStats();
    const lines = [
      a.bold.white("  API Performance"),
      a.dim(`  ${"\u2500".repeat(40)}`)
    ];
    if (stats.length === 0) {
      lines.push(a.dim("  No API calls recorded"));
      return lines;
    }
    const avgLatency = stats.reduce((sum, s) => sum + s.avgLatency, 0) / stats.length;
    this.apiLatencyHistory.push(avgLatency);
    if (this.apiLatencyHistory.length > 60)
      this.apiLatencyHistory.shift();
    for (const provider of stats.slice(0, 3)) {
      const successRate = provider.totalCalls > 0 ? (provider.successCount / provider.totalCalls * 100).toFixed(1) : "0";
      const rateColor = Number(successRate) >= 95 ? a.green : Number(successRate) >= 80 ? a.yellow : a.red;
      lines.push(`  ${a.cyan(provider.provider)}`);
      lines.push(`    ${a.dim("Calls:")} ${provider.totalCalls} | ${a.dim("Success:")} ${rateColor(`${successRate}%`)}`);
      lines.push(`    ${a.dim("Latency:")} ${a.yellow(formatDuration(provider.avgLatency))} (p95: ${formatDuration(provider.p95Latency)})`);
    }
    lines.push(`  ${a.dim("Latency:")} ${generateSparkline(this.apiLatencyHistory, 30)}`);
    return lines;
  }
  /**
   * Render commands section
   */
  renderCommandsSection() {
    const stats = this.collector.getCommandStats();
    const lines = [
      a.bold.white("  Command Execution"),
      a.dim(`  ${"\u2500".repeat(40)}`)
    ];
    if (stats.length === 0) {
      lines.push(a.dim("  No commands recorded"));
      return lines;
    }
    const sorted = [...stats].sort((a, b) => b.totalExecutions - a.totalExecutions).slice(0, 5);
    const chartData = sorted.map((s) => ({
      label: s.command.slice(0, 15),
      value: s.totalExecutions
    }));
    lines.push(...generateBarChart(chartData, { width: 20 }));
    const totalExecs = stats.reduce((sum, s) => sum + s.totalExecutions, 0);
    const totalSuccess = stats.reduce((sum, s) => sum + s.successCount, 0);
    const successRate = totalExecs > 0 ? (totalSuccess / totalExecs * 100).toFixed(1) : "0";
    lines.push("");
    lines.push(`  ${a.dim("Total:")} ${totalExecs} | ${a.dim("Success:")} ${a.green(`${successRate}%`)}`);
    return lines;
  }
  /**
   * Render cache section
   */
  renderCacheSection() {
    const stats = this.collector.getCacheStats();
    const lines = [
      a.bold.white("  Cache Performance"),
      a.dim(`  ${"\u2500".repeat(40)}`)
    ];
    const hitRateBar = generateProgressBar(stats.hitRate, 1, 20, { showPercent: true });
    lines.push(`  Hit Rate: ${hitRateBar}`);
    lines.push(`  ${a.dim("Hits:")} ${a.green(stats.hits.toString())} | ${a.dim("Misses:")} ${a.red(stats.misses.toString())}`);
    lines.push(`  ${a.dim("Avg Latency:")} ${a.yellow(formatDuration(stats.avgLatency))}`);
    lines.push(`  ${a.dim("Items:")} ${stats.itemCount} | ${a.dim("Size:")} ${formatBytes(stats.totalSize)}`);
    return lines;
  }
  /**
   * Render errors section
   */
  renderErrorsSection() {
    const stats = this.collector.getErrorStats();
    const lines = [
      a.bold.white("  Recent Errors"),
      a.dim(`  ${"\u2500".repeat(76)}`)
    ];
    if (stats.totalErrors === 0) {
      lines.push(a.green("  No errors recorded"));
      return lines;
    }
    const severityLine = [
      `${a.red("Critical:")} ${stats.errorsBySeverity.critical}`,
      `${a.red("High:")} ${stats.errorsBySeverity.high}`,
      `${a.yellow("Medium:")} ${stats.errorsBySeverity.medium}`,
      `${a.green("Low:")} ${stats.errorsBySeverity.low}`
    ].join(" | ");
    lines.push(`  ${severityLine}`);
    lines.push("");
    for (const error of stats.recentErrors.slice(0, 3)) {
      const severityIcon = error.severity === "critical" ? a.red("\u25CF") : error.severity === "high" ? a.red("\u25CB") : error.severity === "medium" ? a.yellow("\u25CB") : a.green("\u25CB");
      const time = new Date(error.timestamp).toLocaleTimeString();
      lines.push(`  ${severityIcon} ${a.dim(time)} ${a.cyan(error.type)}: ${error.message.slice(0, 50)}`);
    }
    return lines;
  }
  /**
   * Render agents section
   */
  renderAgentsSection() {
    const stats = this.collector.getAgentStats();
    const lines = [
      a.bold.white("  Agent Tasks"),
      a.dim(`  ${"\u2500".repeat(76)}`)
    ];
    if (stats.length === 0) {
      lines.push(a.dim("  No agent tasks recorded"));
      return lines;
    }
    lines.push(`  ${a.dim("Agent".padEnd(30))} ${a.dim("Tasks".padEnd(8))} ${a.dim("Success".padEnd(10))} ${a.dim("Avg Time")}`);
    for (const agent of stats.slice(0, 5)) {
      const successRate = `${(agent.successRate * 100).toFixed(0)}%`;
      const rateColor = agent.successRate >= 0.95 ? a.green : agent.successRate >= 0.8 ? a.yellow : a.red;
      lines.push(
        `  ${a.cyan(agent.agentName.slice(0, 28).padEnd(30))} ${agent.totalTasks.toString().padEnd(8)} ${rateColor(successRate.padEnd(10))} ${a.yellow(formatDuration(agent.avgDuration))}`
      );
    }
    return lines;
  }
  /**
   * Render footer
   */
  renderFooter() {
    return [
      a.dim("\u2550".repeat(80)),
      a.dim(`  Press Ctrl+C to exit | Refresh: ${this.config.refreshInterval / 1e3}s | ${(/* @__PURE__ */ new Date()).toISOString()}`)
    ];
  }
}
class PerformanceDashboard {
  config;
  collector;
  renderer;
  refreshTimer;
  isRunning = false;
  constructor(config = {}, collector) {
    this.config = { ...DEFAULT_CONFIG, ...config };
    this.collector = collector || getMetricsCollector();
    this.renderer = new DashboardRenderer(this.config, this.collector);
  }
  /**
   * Show the dashboard
   */
  show() {
    if (this.isRunning)
      return;
    this.isRunning = true;
    this.render();
    this.refreshTimer = setInterval(() => {
      this.render();
    }, this.config.refreshInterval);
    process__default.on("SIGINT", () => {
      this.stop();
      process__default.exit(0);
    });
  }
  /**
   * Refresh the dashboard
   */
  refresh() {
    this.render();
  }
  /**
   * Render the dashboard to terminal
   */
  render() {
    process__default.stdout.write("\x1B[2J\x1B[0f");
    const output = this.renderer.render();
    console.log(output);
  }
  /**
   * Stop the dashboard
   */
  stop() {
    this.isRunning = false;
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer);
      this.refreshTimer = void 0;
    }
  }
  /**
   * Export dashboard data
   */
  export(format) {
    const data = this.collectData();
    switch (format) {
      case "json":
        return this.exportJson(data);
      case "csv":
        return this.exportCsv(data);
      case "html":
        return this.exportHtml(data);
      default:
        return this.exportJson(data);
    }
  }
  /**
   * Collect current dashboard data
   */
  collectData() {
    const memStats = this.collector.getMemoryStats();
    const errorStats = this.collector.getErrorStats();
    let health = "healthy";
    if (errorStats.errorsBySeverity.critical > 0)
      health = "critical";
    else if (errorStats.errorsBySeverity.high > 0)
      health = "unhealthy";
    else if (memStats.current.heapUsedPercent > 0.9)
      health = "degraded";
    const system = {
      status: health,
      uptime: this.collector.getUptime(),
      startTime: Date.now() - this.collector.getUptime(),
      version: "1.0.0",
      nodeVersion: process__default.version,
      platform: process__default.platform,
      healthChecks: []
    };
    return {
      timestamp: Date.now(),
      system,
      commands: this.collector.getCommandStats(),
      memory: memStats,
      api: this.collector.getApiStats(),
      cache: this.collector.getCacheStats(),
      errors: errorStats,
      agents: this.collector.getAgentStats()
    };
  }
  /**
   * Export as JSON
   */
  exportJson(data) {
    return JSON.stringify(data, null, 2);
  }
  /**
   * Export as CSV
   */
  exportCsv(data) {
    const lines = [];
    lines.push("# Commands");
    lines.push("command,total,success,failure,avg_duration,p95_duration");
    for (const cmd of data.commands) {
      lines.push(`${cmd.command},${cmd.totalExecutions},${cmd.successCount},${cmd.failureCount},${cmd.avgDuration},${cmd.p95Duration}`);
    }
    lines.push("");
    lines.push("# API Calls");
    lines.push("provider,total,success,failure,avg_latency,p95_latency,tokens");
    for (const api of data.api) {
      lines.push(`${api.provider},${api.totalCalls},${api.successCount},${api.failureCount},${api.avgLatency},${api.p95Latency},${api.totalTokens}`);
    }
    lines.push("");
    lines.push("# Memory");
    lines.push("heap_used,heap_total,rss,heap_percent");
    lines.push(`${data.memory.current.heapUsed},${data.memory.current.heapTotal},${data.memory.current.rss},${data.memory.current.heapUsedPercent}`);
    return lines.join("\n");
  }
  /**
   * Export as HTML
   */
  exportHtml(data) {
    return `<!DOCTYPE html>
<html>
<head>
  <title>CCJK Performance Report</title>
  <style>
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: 20px; background: #1a1a2e; color: #eee; }
    h1 { color: #00d9ff; }
    h2 { color: #00ff88; border-bottom: 1px solid #333; padding-bottom: 10px; }
    .card { background: #16213e; border-radius: 8px; padding: 20px; margin: 20px 0; }
    .metric { display: inline-block; margin: 10px 20px; }
    .metric-value { font-size: 2em; color: #00d9ff; }
    .metric-label { color: #888; }
    table { width: 100%; border-collapse: collapse; }
    th, td { padding: 10px; text-align: left; border-bottom: 1px solid #333; }
    th { color: #00ff88; }
    .status-healthy { color: #00ff88; }
    .status-degraded { color: #ffaa00; }
    .status-unhealthy { color: #ff4444; }
  </style>
</head>
<body>
  <h1>CCJK Performance Report</h1>
  <p>Generated: ${new Date(data.timestamp).toLocaleString()}</p>

  <div class="card">
    <h2>System Overview</h2>
    <div class="metric">
      <div class="metric-value status-${data.system.status}">${data.system.status.toUpperCase()}</div>
      <div class="metric-label">Status</div>
    </div>
    <div class="metric">
      <div class="metric-value">${formatUptime(data.system.uptime)}</div>
      <div class="metric-label">Uptime</div>
    </div>
    <div class="metric">
      <div class="metric-value">${formatBytes(data.memory.current.heapUsed)}</div>
      <div class="metric-label">Memory Used</div>
    </div>
    <div class="metric">
      <div class="metric-value">${data.errors.totalErrors}</div>
      <div class="metric-label">Total Errors</div>
    </div>
  </div>

  <div class="card">
    <h2>Command Statistics</h2>
    <table>
      <tr><th>Command</th><th>Total</th><th>Success</th><th>Failure</th><th>Avg Duration</th></tr>
      ${data.commands.map((c) => `<tr><td>${c.command}</td><td>${c.totalExecutions}</td><td>${c.successCount}</td><td>${c.failureCount}</td><td>${formatDuration(c.avgDuration)}</td></tr>`).join("")}
    </table>
  </div>

  <div class="card">
    <h2>API Performance</h2>
    <table>
      <tr><th>Provider</th><th>Calls</th><th>Success Rate</th><th>Avg Latency</th><th>Tokens</th></tr>
      ${data.api.map((a) => `<tr><td>${a.provider}</td><td>${a.totalCalls}</td><td>${(a.successCount / a.totalCalls * 100).toFixed(1)}%</td><td>${formatDuration(a.avgLatency)}</td><td>${a.totalTokens}</td></tr>`).join("")}
    </table>
  </div>

  <div class="card">
    <h2>Cache Statistics</h2>
    <div class="metric">
      <div class="metric-value">${(data.cache.hitRate * 100).toFixed(1)}%</div>
      <div class="metric-label">Hit Rate</div>
    </div>
    <div class="metric">
      <div class="metric-value">${data.cache.hits}</div>
      <div class="metric-label">Hits</div>
    </div>
    <div class="metric">
      <div class="metric-value">${data.cache.misses}</div>
      <div class="metric-label">Misses</div>
    </div>
  </div>
</body>
</html>`;
  }
}
function createDashboard(config) {
  return new PerformanceDashboard(config);
}

const DEFAULT_REPORT_CONFIG = {
  timeRange: "daily",
  includeCommands: true,
  includeMemory: true,
  includeApi: true,
  includeCache: true,
  includeErrors: true,
  includeAgents: true,
  includeTrends: true,
  includeAnomalies: true
};
function getTimeRangeBoundaries(range, custom) {
  const now = Date.now();
  const end = custom?.end || now;
  switch (range) {
    case "hourly":
      return { start: end - 60 * 60 * 1e3, end };
    case "daily":
      return { start: end - 24 * 60 * 60 * 1e3, end };
    case "weekly":
      return { start: end - 7 * 24 * 60 * 60 * 1e3, end };
    case "monthly":
      return { start: end - 30 * 24 * 60 * 60 * 1e3, end };
    case "custom":
      return {
        start: custom?.start || end - 24 * 60 * 60 * 1e3,
        end
      };
    default:
      return { start: end - 24 * 60 * 60 * 1e3, end };
  }
}
function analyzeTrend(values, metricName) {
  if (values.length < 2) {
    return {
      metric: metricName,
      direction: "stable",
      changePercent: 0,
      significance: "low"
    };
  }
  const midpoint = Math.floor(values.length / 2);
  const firstHalf = values.slice(0, midpoint);
  const secondHalf = values.slice(midpoint);
  const firstAvg = firstHalf.reduce((a, b) => a + b, 0) / firstHalf.length;
  const secondAvg = secondHalf.reduce((a, b) => a + b, 0) / secondHalf.length;
  const changePercent = firstAvg !== 0 ? (secondAvg - firstAvg) / firstAvg * 100 : secondAvg > 0 ? 100 : 0;
  let direction = "stable";
  if (changePercent > 5)
    direction = "up";
  else if (changePercent < -5)
    direction = "down";
  let significance = "low";
  const absChange = Math.abs(changePercent);
  if (absChange > 50)
    significance = "high";
  else if (absChange > 20)
    significance = "medium";
  const slope = (secondAvg - firstAvg) / midpoint;
  const prediction = secondAvg + slope * midpoint;
  return {
    metric: metricName,
    direction,
    changePercent,
    significance,
    prediction: prediction > 0 ? prediction : void 0
  };
}
function generateRecommendations(commands, api, cache, errors, memory, agents) {
  const recommendations = [];
  const slowCommands = commands.filter((c) => c.avgDuration > 5e3);
  if (slowCommands.length > 0) {
    recommendations.push(
      `Consider optimizing slow commands: ${slowCommands.map((c) => c.command).join(", ")} (avg > 5s)`
    );
  }
  const failingCommands = commands.filter((c) => c.failureCount / c.totalExecutions > 0.1);
  if (failingCommands.length > 0) {
    recommendations.push(
      `Investigate high failure rate commands: ${failingCommands.map((c) => c.command).join(", ")} (>10% failure)`
    );
  }
  const slowApis = api.filter((a) => a.avgLatency > 3e3);
  if (slowApis.length > 0) {
    recommendations.push(
      `API latency is high for: ${slowApis.map((a) => a.provider).join(", ")} (avg > 3s). Consider caching or optimization.`
    );
  }
  const highErrorApis = api.filter((a) => a.errorRate > 0.05);
  if (highErrorApis.length > 0) {
    recommendations.push(
      `High API error rate for: ${highErrorApis.map((a) => a.provider).join(", ")} (>5%). Check API health and credentials.`
    );
  }
  if (cache.hitRate < 0.5 && cache.totalOperations > 100) {
    recommendations.push(
      `Cache hit rate is low (${(cache.hitRate * 100).toFixed(1)}%). Consider reviewing cache strategy and TTL settings.`
    );
  }
  if (cache.evictions > cache.totalOperations * 0.2) {
    recommendations.push(
      `High cache eviction rate. Consider increasing cache size or adjusting eviction policy.`
    );
  }
  if (errors.errorsBySeverity.critical > 0) {
    recommendations.push(
      `Critical errors detected (${errors.errorsBySeverity.critical}). Immediate investigation required.`
    );
  }
  if (errors.errorRate > 1) {
    recommendations.push(
      `Error rate is high (${errors.errorRate.toFixed(2)}/min). Review error logs and implement error handling.`
    );
  }
  if (memory.current.heapUsedPercent > 0.8) {
    recommendations.push(
      `Memory usage is high (${(memory.current.heapUsedPercent * 100).toFixed(1)}%). Consider memory optimization or increasing heap size.`
    );
  }
  if (memory.trend === "increasing") {
    recommendations.push(
      `Memory usage is trending upward. Monitor for potential memory leaks.`
    );
  }
  const lowSuccessAgents = agents.filter((a) => a.successRate < 0.8);
  if (lowSuccessAgents.length > 0) {
    recommendations.push(
      `Low success rate for agents: ${lowSuccessAgents.map((a) => a.agentName).join(", ")} (<80%). Review agent configurations.`
    );
  }
  if (recommendations.length === 0) {
    recommendations.push("System is performing well. No immediate optimizations needed.");
  }
  return recommendations;
}
class PerformanceReporter {
  collector;
  config;
  constructor(config = {}, collector) {
    this.config = { ...DEFAULT_REPORT_CONFIG, ...config };
    this.collector = collector || getMetricsCollector();
  }
  /**
   * Generate a performance report
   */
  generateReport(config) {
    const reportConfig = { ...this.config, ...config };
    const { start, end } = getTimeRangeBoundaries(
      reportConfig.timeRange,
      { start: reportConfig.startTime, end: reportConfig.endTime }
    );
    const commands = reportConfig.includeCommands ? this.collector.getCommandStats() : [];
    const api = reportConfig.includeApi ? this.collector.getApiStats() : [];
    const cache = reportConfig.includeCache ? this.collector.getCacheStats() : { totalOperations: 0, hits: 0, misses: 0, hitRate: 0, avgLatency: 0, totalSize: 0, itemCount: 0, evictions: 0 };
    const errors = reportConfig.includeErrors ? this.collector.getErrorStats() : { totalErrors: 0, errorsByType: {}, errorsBySeverity: { low: 0, medium: 0, high: 0, critical: 0 }, errorRate: 0, recentErrors: [] };
    const memory = reportConfig.includeMemory ? this.collector.getMemoryStats() : this.getEmptyMemoryStats();
    const agents = reportConfig.includeAgents ? this.collector.getAgentStats() : [];
    const totalCommands = commands.reduce((sum, c) => sum + c.totalExecutions, 0);
    const avgCommandDuration = commands.length > 0 ? commands.reduce((sum, c) => sum + c.avgDuration * c.totalExecutions, 0) / totalCommands : 0;
    const totalApiCalls = api.reduce((sum, a) => sum + a.totalCalls, 0);
    const avgApiLatency = api.length > 0 ? api.reduce((sum, a) => sum + a.avgLatency * a.totalCalls, 0) / totalApiCalls : 0;
    const trends = [];
    if (reportConfig.includeTrends) {
      if (commands.length > 0) {
        const durations = commands.map((c) => c.avgDuration);
        trends.push(analyzeTrend(durations, "command.avgDuration"));
      }
      if (api.length > 0) {
        const latencies = api.map((a) => a.avgLatency);
        trends.push(analyzeTrend(latencies, "api.avgLatency"));
      }
      trends.push(analyzeTrend([errors.errorRate], "error.rate"));
      trends.push({
        metric: "memory.heapUsed",
        direction: memory.trend === "increasing" ? "up" : memory.trend === "decreasing" ? "down" : "stable",
        changePercent: 0,
        significance: memory.trend === "increasing" ? "medium" : "low"
      });
    }
    const anomalies = [];
    if (reportConfig.includeAnomalies) {
      for (const cmd of commands) {
        if (cmd.avgDuration > cmd.p95Duration * 1.5) {
          anomalies.push({
            metric: `command.${cmd.command}.duration`,
            timestamp: cmd.lastExecution || Date.now(),
            value: cmd.avgDuration,
            expectedValue: cmd.p95Duration,
            deviation: (cmd.avgDuration - cmd.p95Duration) / cmd.p95Duration,
            severity: "medium",
            description: `Command ${cmd.command} average duration exceeds p95`
          });
        }
      }
      for (const a of api) {
        if (a.errorRate > 0.1) {
          anomalies.push({
            metric: `api.${a.provider}.errorRate`,
            timestamp: Date.now(),
            value: a.errorRate,
            expectedValue: 0.01,
            deviation: a.errorRate / 0.01,
            severity: a.errorRate > 0.5 ? "critical" : a.errorRate > 0.2 ? "high" : "medium",
            description: `API ${a.provider} has high error rate (${(a.errorRate * 100).toFixed(1)}%)`
          });
        }
      }
    }
    const recommendations = generateRecommendations(commands, api, cache, errors, memory, agents);
    return {
      id: `report_${Date.now()}`,
      generatedAt: Date.now(),
      timeRange: { start, end },
      summary: {
        totalCommands,
        avgCommandDuration,
        totalApiCalls,
        avgApiLatency,
        cacheHitRate: cache.hitRate,
        errorRate: errors.errorRate,
        memoryUsage: memory.current.heapUsedPercent
      },
      commands,
      api,
      cache,
      errors,
      agents,
      trends,
      anomalies,
      recommendations
    };
  }
  /**
   * Generate a daily report
   */
  generateDailyReport() {
    return this.generateReport({ timeRange: "daily" });
  }
  /**
   * Generate a weekly report
   */
  generateWeeklyReport() {
    return this.generateReport({ timeRange: "weekly" });
  }
  /**
   * Generate a monthly report
   */
  generateMonthlyReport() {
    return this.generateReport({ timeRange: "monthly" });
  }
  /**
   * Format report as text
   */
  formatReportAsText(report) {
    const lines = [];
    const separator = "\u2550".repeat(60);
    const thinSeparator = "\u2500".repeat(60);
    lines.push(separator);
    lines.push("  CCJK Performance Report");
    lines.push(`  Generated: ${new Date(report.generatedAt).toLocaleString()}`);
    lines.push(`  Period: ${new Date(report.timeRange.start).toLocaleDateString()} - ${new Date(report.timeRange.end).toLocaleDateString()}`);
    lines.push(separator);
    lines.push("");
    lines.push("  SUMMARY");
    lines.push(thinSeparator);
    lines.push(`  Total Commands: ${report.summary.totalCommands}`);
    lines.push(`  Avg Command Duration: ${report.summary.avgCommandDuration.toFixed(0)}ms`);
    lines.push(`  Total API Calls: ${report.summary.totalApiCalls}`);
    lines.push(`  Avg API Latency: ${report.summary.avgApiLatency.toFixed(0)}ms`);
    lines.push(`  Cache Hit Rate: ${(report.summary.cacheHitRate * 100).toFixed(1)}%`);
    lines.push(`  Error Rate: ${report.summary.errorRate.toFixed(2)}/min`);
    lines.push(`  Memory Usage: ${(report.summary.memoryUsage * 100).toFixed(1)}%`);
    lines.push("");
    if (report.commands.length > 0) {
      lines.push("  COMMAND STATISTICS");
      lines.push(thinSeparator);
      for (const cmd of report.commands.slice(0, 10)) {
        const successRate = cmd.totalExecutions > 0 ? (cmd.successCount / cmd.totalExecutions * 100).toFixed(1) : "0";
        lines.push(`  ${cmd.command}`);
        lines.push(`    Executions: ${cmd.totalExecutions} | Success: ${successRate}% | Avg: ${cmd.avgDuration.toFixed(0)}ms`);
      }
      lines.push("");
    }
    if (report.api.length > 0) {
      lines.push("  API PERFORMANCE");
      lines.push(thinSeparator);
      for (const api of report.api) {
        lines.push(`  ${api.provider}`);
        lines.push(`    Calls: ${api.totalCalls} | Latency: ${api.avgLatency.toFixed(0)}ms | Errors: ${(api.errorRate * 100).toFixed(1)}%`);
      }
      lines.push("");
    }
    if (report.trends.length > 0) {
      lines.push("  TRENDS");
      lines.push(thinSeparator);
      for (const trend of report.trends) {
        const arrow = trend.direction === "up" ? "\u2191" : trend.direction === "down" ? "\u2193" : "\u2192";
        lines.push(`  ${trend.metric}: ${arrow} ${trend.changePercent.toFixed(1)}% (${trend.significance})`);
      }
      lines.push("");
    }
    if (report.anomalies.length > 0) {
      lines.push("  ANOMALIES DETECTED");
      lines.push(thinSeparator);
      for (const anomaly of report.anomalies.slice(0, 5)) {
        lines.push(`  [${anomaly.severity.toUpperCase()}] ${anomaly.description}`);
      }
      lines.push("");
    }
    if (report.recommendations.length > 0) {
      lines.push("  RECOMMENDATIONS");
      lines.push(thinSeparator);
      for (const rec of report.recommendations) {
        lines.push(`  \u2022 ${rec}`);
      }
      lines.push("");
    }
    lines.push(separator);
    return lines.join("\n");
  }
  /**
   * Format report as JSON
   */
  formatReportAsJson(report) {
    return JSON.stringify(report, null, 2);
  }
  /**
   * Format report as HTML
   */
  formatReportAsHtml(report) {
    return `<!DOCTYPE html>
<html>
<head>
  <title>CCJK Performance Report - ${new Date(report.generatedAt).toLocaleDateString()}</title>
  <style>
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: 0; padding: 20px; background: #0d1117; color: #c9d1d9; }
    .container { max-width: 1200px; margin: 0 auto; }
    h1 { color: #58a6ff; border-bottom: 1px solid #30363d; padding-bottom: 10px; }
    h2 { color: #7ee787; margin-top: 30px; }
    .card { background: #161b22; border: 1px solid #30363d; border-radius: 6px; padding: 20px; margin: 15px 0; }
    .metric-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; }
    .metric { text-align: center; padding: 15px; background: #21262d; border-radius: 6px; }
    .metric-value { font-size: 2em; color: #58a6ff; font-weight: bold; }
    .metric-label { color: #8b949e; font-size: 0.9em; }
    table { width: 100%; border-collapse: collapse; margin: 10px 0; }
    th, td { padding: 12px; text-align: left; border-bottom: 1px solid #30363d; }
    th { color: #7ee787; font-weight: 600; }
    .trend-up { color: #f85149; }
    .trend-down { color: #7ee787; }
    .trend-stable { color: #8b949e; }
    .severity-critical { color: #f85149; font-weight: bold; }
    .severity-high { color: #f85149; }
    .severity-medium { color: #d29922; }
    .severity-low { color: #7ee787; }
    .recommendation { padding: 10px 15px; background: #21262d; border-left: 3px solid #58a6ff; margin: 10px 0; }
    .footer { text-align: center; color: #8b949e; margin-top: 30px; padding-top: 20px; border-top: 1px solid #30363d; }
  </style>
</head>
<body>
  <div class="container">
    <h1>CCJK Performance Report</h1>
    <p>Generated: ${new Date(report.generatedAt).toLocaleString()}</p>
    <p>Period: ${new Date(report.timeRange.start).toLocaleDateString()} - ${new Date(report.timeRange.end).toLocaleDateString()}</p>

    <h2>Summary</h2>
    <div class="card">
      <div class="metric-grid">
        <div class="metric">
          <div class="metric-value">${report.summary.totalCommands}</div>
          <div class="metric-label">Total Commands</div>
        </div>
        <div class="metric">
          <div class="metric-value">${report.summary.avgCommandDuration.toFixed(0)}ms</div>
          <div class="metric-label">Avg Command Duration</div>
        </div>
        <div class="metric">
          <div class="metric-value">${report.summary.totalApiCalls}</div>
          <div class="metric-label">API Calls</div>
        </div>
        <div class="metric">
          <div class="metric-value">${report.summary.avgApiLatency.toFixed(0)}ms</div>
          <div class="metric-label">Avg API Latency</div>
        </div>
        <div class="metric">
          <div class="metric-value">${(report.summary.cacheHitRate * 100).toFixed(1)}%</div>
          <div class="metric-label">Cache Hit Rate</div>
        </div>
        <div class="metric">
          <div class="metric-value">${(report.summary.memoryUsage * 100).toFixed(1)}%</div>
          <div class="metric-label">Memory Usage</div>
        </div>
      </div>
    </div>

    ${report.commands.length > 0 ? `
    <h2>Command Statistics</h2>
    <div class="card">
      <table>
        <tr><th>Command</th><th>Executions</th><th>Success Rate</th><th>Avg Duration</th><th>P95 Duration</th></tr>
        ${report.commands.map((c) => `
        <tr>
          <td>${c.command}</td>
          <td>${c.totalExecutions}</td>
          <td>${(c.successCount / c.totalExecutions * 100).toFixed(1)}%</td>
          <td>${c.avgDuration.toFixed(0)}ms</td>
          <td>${c.p95Duration.toFixed(0)}ms</td>
        </tr>`).join("")}
      </table>
    </div>` : ""}

    ${report.api.length > 0 ? `
    <h2>API Performance</h2>
    <div class="card">
      <table>
        <tr><th>Provider</th><th>Calls</th><th>Success Rate</th><th>Avg Latency</th><th>P95 Latency</th><th>Tokens</th></tr>
        ${report.api.map((a) => `
        <tr>
          <td>${a.provider}</td>
          <td>${a.totalCalls}</td>
          <td>${((1 - a.errorRate) * 100).toFixed(1)}%</td>
          <td>${a.avgLatency.toFixed(0)}ms</td>
          <td>${a.p95Latency.toFixed(0)}ms</td>
          <td>${a.totalTokens}</td>
        </tr>`).join("")}
      </table>
    </div>` : ""}

    ${report.trends.length > 0 ? `
    <h2>Trends</h2>
    <div class="card">
      <table>
        <tr><th>Metric</th><th>Direction</th><th>Change</th><th>Significance</th></tr>
        ${report.trends.map((t) => `
        <tr>
          <td>${t.metric}</td>
          <td class="trend-${t.direction}">${t.direction === "up" ? "\u2191 Up" : t.direction === "down" ? "\u2193 Down" : "\u2192 Stable"}</td>
          <td>${t.changePercent.toFixed(1)}%</td>
          <td>${t.significance}</td>
        </tr>`).join("")}
      </table>
    </div>` : ""}

    ${report.anomalies.length > 0 ? `
    <h2>Anomalies Detected</h2>
    <div class="card">
      ${report.anomalies.map((a) => `
      <div class="recommendation">
        <span class="severity-${a.severity}">[${a.severity.toUpperCase()}]</span> ${a.description}
      </div>`).join("")}
    </div>` : ""}

    <h2>Recommendations</h2>
    <div class="card">
      ${report.recommendations.map((r) => `<div class="recommendation">${r}</div>`).join("")}
    </div>

    <div class="footer">
      <p>Generated by CCJK Performance Monitor</p>
    </div>
  </div>
</body>
</html>`;
  }
  /**
   * Get empty memory stats
   */
  getEmptyMemoryStats() {
    const emptySnapshot = {
      timestamp: Date.now(),
      heapUsed: 0,
      heapTotal: 0,
      external: 0,
      arrayBuffers: 0,
      rss: 0,
      heapUsedPercent: 0
    };
    return {
      current: emptySnapshot,
      peak: emptySnapshot,
      average: { heapUsed: 0, heapTotal: 0, rss: 0 },
      trend: "stable"
    };
  }
}
function createReporter(config) {
  return new PerformanceReporter(config);
}

async function monitor(subcommand, options = {}) {
  const isZh = (options.lang || i18n.language) === "zh-CN";
  if (!options.noBanner) {
    displayBannerWithInfo();
  }
  switch (subcommand) {
    case "start":
      await monitorStart(options);
      break;
    case "stop":
      console.log(a.dim(isZh ? "\u63D0\u793A: \u6309 Ctrl+C \u9000\u51FA\u76D1\u63A7\u9762\u677F" : "Tip: Press Ctrl+C to exit the dashboard"));
      break;
    case "report":
      await monitorReport(options);
      break;
    case "export":
      await monitorExport(options);
      break;
    case "help":
      monitorHelp(options);
      break;
    default:
      await monitorStart(options);
      break;
  }
}
async function monitorStart(options) {
  const isZh = (options.lang || i18n.language) === "zh-CN";
  const refreshMs = options.refresh ? Number.parseInt(options.refresh, 10) * 1e3 : void 0;
  const config = {
    refreshInterval: refreshMs || 2e3,
    showCommands: true,
    showMemory: true,
    showApi: true,
    showCache: true,
    showErrors: true,
    showAgents: true
  };
  console.log("");
  console.log(a.bold.cyan(isZh ? "\u{1F4CA} \u542F\u52A8 CCJK \u6027\u80FD\u76D1\u63A7\u9762\u677F..." : "\u{1F4CA} Starting CCJK Performance Monitor..."));
  console.log("");
  console.log(a.dim(isZh ? "\u63D0\u793A: \u6309 Ctrl+C \u9000\u51FA\u76D1\u63A7" : "Tip: Press Ctrl+C to exit monitoring"));
  console.log("");
  const dashboard = createDashboard(config);
  dashboard.show();
}
async function monitorReport(options) {
  const isZh = (options.lang || i18n.language) === "zh-CN";
  const timeRange = options.range || "daily";
  console.log("");
  console.log(a.bold.cyan(isZh ? "\u{1F4C8} \u751F\u6210\u6027\u80FD\u62A5\u544A..." : "\u{1F4C8} Generating Performance Report..."));
  console.log("");
  const reporter = createReporter({ timeRange });
  const report = reporter.generateReport();
  const reportText = reporter.formatReportAsText(report);
  console.log(reportText);
  if (options.output) {
    const fs = await import('node:fs/promises');
    await fs.writeFile(options.output, reportText);
    console.log("");
    console.log(a.green(`${isZh ? "\u62A5\u544A\u5DF2\u4FDD\u5B58\u5230" : "Report saved to"} ${options.output}`));
  }
  if (options.json) {
    const jsonReport = reporter.formatReportAsJson(report);
    const jsonOutput = options.output ? options.output.replace(/\.[^.]+$/, ".json") : "ccjk-monitor-report.json";
    const fs = await import('node:fs/promises');
    await fs.writeFile(jsonOutput, jsonReport);
    console.log(a.green(`${isZh ? "JSON \u62A5\u544A\u5DF2\u4FDD\u5B58\u5230" : "JSON report saved to"} ${jsonOutput}`));
  }
  console.log("");
}
async function monitorExport(options = {}) {
  const isZh = (options.lang || i18n.language) === "zh-CN";
  const format = options.format || "json";
  console.log("");
  console.log(a.bold.cyan(isZh ? "\u{1F4BE} \u5BFC\u51FA\u76D1\u63A7\u6570\u636E..." : "\u{1F4BE} Exporting Monitoring Data..."));
  console.log("");
  const dashboard = createDashboard();
  const data = dashboard.export(format);
  let outputFile = options.output;
  if (!outputFile) {
    const ext = format === "csv" ? "csv" : format === "html" ? "html" : "json";
    outputFile = `ccjk-metrics-${Date.now()}.${ext}`;
  }
  const fs = await import('node:fs/promises');
  await fs.writeFile(outputFile, data);
  console.log(a.green(`${isZh ? "\u6570\u636E\u5DF2\u5BFC\u51FA\u5230" : "Data exported to"} ${outputFile}`));
  console.log("");
}
function monitorHelp(options = {}) {
  const isZh = (options.lang || i18n.language) === "zh-CN";
  console.log("");
  console.log(a.bold.cyan(isZh ? "\u{1F4CA} CCJK \u6027\u80FD\u76D1\u63A7\u547D\u4EE4" : "\u{1F4CA} CCJK Performance Monitor Commands"));
  console.log(a.dim("\u2500".repeat(60)));
  console.log("");
  const commands = [
    {
      cmd: "ccjk monitor",
      desc: isZh ? "\u542F\u52A8\u5B9E\u65F6\u76D1\u63A7\u9762\u677F" : "Start real-time monitoring dashboard"
    },
    {
      cmd: "ccjk monitor start",
      desc: isZh ? "\u542F\u52A8\u5B9E\u65F6\u76D1\u63A7\u9762\u677F" : "Start real-time monitoring dashboard"
    },
    {
      cmd: "ccjk monitor report",
      desc: isZh ? "\u751F\u6210\u6027\u80FD\u62A5\u544A" : "Generate performance report"
    },
    {
      cmd: "ccjk monitor export",
      desc: isZh ? "\u5BFC\u51FA\u76D1\u63A7\u6570\u636E" : "Export monitoring data"
    },
    {
      cmd: "ccjk monitor help",
      desc: isZh ? "\u663E\u793A\u5E2E\u52A9\u4FE1\u606F" : "Show help information"
    }
  ];
  for (const { cmd, desc } of commands) {
    console.log(`  ${a.green(cmd)}`);
    console.log(`    ${a.dim(desc)}`);
    console.log("");
  }
  console.log(a.bold.yellow(isZh ? "\u9009\u9879:" : "Options:"));
  console.log("");
  console.log(`  ${a.cyan("--refresh, -r <ms>")}     ${isZh ? "\u5237\u65B0\u95F4\u9694 (\u6BEB\u79D2)" : "Refresh interval (milliseconds)"}`);
  console.log(`  ${a.cyan("--range <timeRange>")}   ${isZh ? "\u62A5\u544A\u65F6\u95F4\u8303\u56F4 (hourly|daily|weekly|monthly)" : "Report time range (hourly|daily|weekly|monthly)"}`);
  console.log(`  ${a.cyan("--format, -f <format>")} ${isZh ? "\u5BFC\u51FA\u683C\u5F0F (json|csv|html)" : "Export format (json|csv|html)"}`);
  console.log(`  ${a.cyan("--output, -o <file>")}   ${isZh ? "\u8F93\u51FA\u6587\u4EF6\u8DEF\u5F84" : "Output file path"}`);
  console.log(`  ${a.cyan("--json")}                ${isZh ? "\u540C\u65F6\u8F93\u51FA JSON \u683C\u5F0F" : "Also output JSON format"}`);
  console.log(`  ${a.cyan("--no-banner")}           ${isZh ? "\u4E0D\u663E\u793A\u6A2A\u5E45" : "Do not display banner"}`);
  console.log("");
  console.log(a.dim(isZh ? "\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 ccjk monitor \u542F\u52A8\u5B9E\u65F6\u76D1\u63A7\u9762\u677F\uFF0C\u6309 Ctrl+C \u9000\u51FA" : '\u{1F4A1} Tip: Run "ccjk monitor" to start the dashboard, press Ctrl+C to exit'));
  console.log("");
}

export { monitor };
