// src/lib/awareness/collective/analysis/confidence-surge.ts
import { ChartDataPoint } from '../components/charts/types';

export interface ConfidenceSurge {
  timestamp: number;
  confidence: number;
  delta: number;
  trendValue: number;
}

export function detectConfidenceSurges(
  data: ChartDataPoint[],
  windowSize: number = 5,
  sigma: number = 2
): ConfidenceSurge[] {
  if (data.length < windowSize) return [];

  const surges: ConfidenceSurge[] = [];
  const confs = data.map((d) => d.confidence);
  const mean = confs.reduce((a, b) => a + b, 0) / confs.length;
  const variance = confs.reduce((s, v) => s + Math.pow(v - mean, 2), 0) / confs.length;
  const stdDev = Math.sqrt(variance);

  for (let i = 1; i < data.length; i++) {
    const delta = data[i].confidence - data[i - 1].confidence;
    if (Math.abs(delta) > sigma * stdDev) {
      surges.push({
        timestamp: data[i].timestamp,
        confidence: data[i].confidence,
        delta,
        trendValue: data[i].trendValue,
      });
    }
  }

  return surges;
}
