// lib/evolution/timeline.align.ts
import { getEvolutionLogs } from './history.collector';
/**
 * Timeline Alignment Layer
 * ------------------------
 * 1. يوحّد timestamps إلى وحدة زمنية ثابتة (day أو hour)
 * 2. يحسب التغيّر النسبي بين القيم المتتابعة
 * 3. يضيف مؤشر الاتجاه trendDirection (+, -, stable)
 */

export type AlignedPoint = {
  t: string;
  deltaStability?: number;
  deltaAdaptation?: number;
  trend?: 'up' | 'down' | 'stable';
  stability: number;
  adaptationRate: number;
};

export function alignEvolutionTimeline(mode: 'daily' | 'hourly' = 'daily'): AlignedPoint[] {
  const history = getEvolutionLogs();
  if (!Array.isArray(history) || history.length === 0) return [];

  // ✅ Group by day/hour
  const groupKey = (iso: string) => {
    const d = new Date(iso);
    return mode === 'hourly'
      ? d.toISOString().slice(0, 13) // YYYY-MM-DDTHH
      : d.toISOString().slice(0, 10); // YYYY-MM-DD
  };

  const grouped: Record<string, any[]> = {};
  history.forEach((s) => {
    // EvolutionLog uses `timestamp` (ISO string)
    const key = groupKey((s as any).timestamp || (s as any).ts);
    grouped[key] = grouped[key] || [];
    grouped[key].push(s);
  });

  // ✅ Average metrics per group
  const aligned: AlignedPoint[] = Object.entries(grouped).map(([k, arr]) => {
    // The current EvolutionLog shape exposes `confidence` and `changeRate`.
    // Map them into `stability` and `adaptationRate` for alignment.
    const stability = arr.reduce((a, b) => a + ((b as any).confidence ?? 0), 0) / arr.length || 0;
    const adaptationRate =
      arr.reduce((a, b) => a + ((b as any).changeRate ?? 0), 0) / arr.length || 0;
    return { t: k, stability, adaptationRate };
  });

  // ✅ Compute deltas and trends
  for (let i = 1; i < aligned.length; i++) {
    const prev = aligned[i - 1];
    const cur = aligned[i];
    cur.deltaStability = cur.stability - (prev.stability ?? 0);
    cur.deltaAdaptation = cur.adaptationRate - (prev.adaptationRate ?? 0);
    const avgDelta = (cur.deltaStability + cur.deltaAdaptation) / 2;
    cur.trend = avgDelta > 0.001 ? 'up' : avgDelta < -0.001 ? 'down' : 'stable';
  }

  return aligned;
}
