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

export interface StabilityZone {
  start: number;
  end: number;
  trend: number;
}

export function detectStabilityZones(
  data: ChartDataPoint[],
  windowSize: number = 5,
  threshold: number = 5
): StabilityZone[] {
  if (data.length < windowSize) return [];

  const zones: StabilityZone[] = [];
  let startIndex = 0;

  for (let i = 0; i < data.length - windowSize; i++) {
    const slice = data.slice(i, i + windowSize);
    const avgChange = slice.reduce((s, l) => s + Math.abs(l.changeRate), 0) / slice.length;

    if (avgChange < threshold) {
      if (zones.length === 0 || i > startIndex + windowSize) {
        startIndex = i;
        zones.push({
          start: data[i].timestamp,
          end: data[i + windowSize - 1].timestamp,
          trend: data[i].trendValue,
        });
      } else {
        zones[zones.length - 1].end = data[i + windowSize - 1].timestamp;
      }
    }
  }

  return zones;
}
