// src/lib/awareness/collective/components/charts/data-mapper.ts
import { EvolutionLog } from '@/lib/evolution/history.collector';
import { ChartDataPoint } from './types';

/** تحويل أسماء الاتجاهات إلى أرقام */
const trendValueMap = { Integrate: 1, Reform: 2, Reset: 3 } as const;

/** يحوّل اللوجز الخام إلى نقاط رسم مرتّبة زمنيًا */
export function mapLogsToChartData(logs: EvolutionLog[]): ChartDataPoint[] {
  if (!Array.isArray(logs)) return [];
  return logs
    .map((log) => ({
      timestamp: new Date(log.timestamp).getTime(),
      trendValue: trendValueMap[log.trend],
      originalTrend: log.trend,
      confidence: log.confidence,
      changeRate: log.changeRate,
      notes: log.notes,
    }))
    .sort((a, b) => a.timestamp - b.timestamp);
}

/**
 * لو البيانات ضخمة (> threshold) بيجّمعها يوميًا لتسريع الرسم
 */
export function downsampleDaily(rows: ChartDataPoint[], threshold = 1000): ChartDataPoint[] {
  if (rows.length <= threshold) return rows;

  const byDay = new Map<string, ChartDataPoint[]>();
  for (const r of rows) {
    const d = new Date(r.timestamp);
    const key = `${d.getUTCFullYear()}-${d.getUTCMonth() + 1}-${d.getUTCDate()}`;
    const arr = byDay.get(key) ?? [];
    arr.push(r);
    byDay.set(key, arr);
  }

  const out: ChartDataPoint[] = [];
  for (const [key, arr] of byDay) {
    const freq: Record<number, number> = { 1: 0, 2: 0, 3: 0 };
    let tsSum = 0,
      confSum = 0,
      crSum = 0;
    for (const r of arr) {
      freq[r.trendValue]++;
      tsSum += r.timestamp;
      confSum += r.confidence;
      crSum += r.changeRate;
    }
    const trendValue = Object.entries(freq).sort((a, b) => b[1] - a[1])[0][0] as unknown as
      | 1
      | 2
      | 3;
    const originalTrend = trendValue === 1 ? 'Integrate' : trendValue === 2 ? 'Reform' : 'Reset';
    out.push({
      timestamp: Math.round(tsSum / arr.length),
      trendValue,
      originalTrend,
      confidence: confSum / arr.length,
      changeRate: crSum / arr.length,
    });
  }

  return out.sort((a, b) => a.timestamp - b.timestamp);
}
