/**
 * @file report.ts
 * تحويل اللوجات إلى CSV/JSON + تنزيل المتصفح
 */
import { EvolutionLog } from '@/lib/evolution/history.collector';

export function toCSV(rows: EvolutionLog[]): string {
  const header = ['timestamp', 'trend', 'confidence', 'changeRate', 'notes'].join(',');
  const body = rows
    .map((r) =>
      [
        r.timestamp,
        r.trend,
        (r.confidence * 100).toFixed(1) + '%',
        r.changeRate.toFixed(2) + '%',
        r.notes ? `"${r.notes.replace(/"/g, '""')}"` : '',
      ].join(',')
    )
    .join('\n');
  return header + '\n' + body;
}

export function toJSON(rows: EvolutionLog[]): string {
  return JSON.stringify(rows, null, 2);
}

export function download(filename: string, content: string, type = 'text/plain') {
  if (typeof document === 'undefined') return;
  const blob = new Blob([content], { type });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  a.remove();
  setTimeout(() => URL.revokeObjectURL(url), 500);
}
