// // lib/evolution/history.collector.ts
// import { readEvolutionReport } from '@/lib/telemetry/evolution.telemetry';

// /**
//  * Snapshot Aggregator — Phase 8 Final Enhancement
//  * يجمع آخر تقارير التطور ويخزنها كـ history timeline.
//  */
// export function appendEvolutionSnapshot() {
//   const report = readEvolutionReport();
//   if (!report?.lastContext) return;

//   const snapshot = {
//     ts: new Date().toISOString(),
//     device: report.lastContext.device,
//     perfMode: report.lastContext.perfMode,
//     animations: report.lastContext.animations,
//     density: report.lastContext.density,
//     confidence: report.lastContext.confidence ?? 0,
//     metrics: report.metrics ?? {},
//   };

//   try {
//     const key = 'EVOLUTION_HISTORY';
//     const prev = JSON.parse(localStorage.getItem(key) || '[]');
//     prev.push(snapshot);
//     localStorage.setItem(key, JSON.stringify(prev.slice(-50)));
//     return snapshot;
//   } catch {
//     return null;
//   }
// }

// /** قراءة كل snapshots */
// export function readEvolutionHistory() {
//   try {
//     const key = 'EVOLUTION_HISTORY';
//     return JSON.parse(localStorage.getItem(key) || '[]');
//   } catch {
//     return [];
//   }
// }

/**
 * @file history.collector.ts
 * Evolution Logs & Auto-Snapshot + Export helpers
 * تخزين خفيف على localStorage (قابل للاستبدال بـ IndexedDB لاحقاً)
 */

import { generateMetaForecast, MetaForecastResult } from './meta-forecast';
import { getTimelineHistory } from './timeline';

const STORAGE_KEY = 'os:evo:logs:v1';

export interface EvolutionLog {
  id: string;
  timestamp: string; // ISO
  trend: MetaForecastResult['trend'];
  confidence: number; // 0..1
  changeRate: number; // %
  notes?: string;
}

let _cache: EvolutionLog[] | null = null;

// -------- Storage ----------
function readAll(): EvolutionLog[] {
  if (_cache) return _cache;
  if (typeof window === 'undefined') return [];
  try {
    const raw = window.localStorage.getItem(STORAGE_KEY);
    _cache = raw ? (JSON.parse(raw) as EvolutionLog[]) : [];
    return _cache;
  } catch {
    return (_cache = []);
  }
}

function writeAll(rows: EvolutionLog[]) {
  _cache = rows;
  if (typeof window === 'undefined') return;
  window.localStorage.setItem(STORAGE_KEY, JSON.stringify(rows));
}

// -------- Public API ----------
export function getEvolutionLogs(): EvolutionLog[] {
  return readAll()
    .slice()
    .sort((a, b) => a.timestamp.localeCompare(b.timestamp));
}

export function clearEvolutionLogs() {
  writeAll([]);
}

export function logSnapshot(partial?: Partial<EvolutionLog>): EvolutionLog {
  const forecast = generateMetaForecast();
  const row: EvolutionLog = {
    id: cryptoRandomId(),
    timestamp: new Date().toISOString(),
    trend: forecast.trend,
    confidence: forecast.confidence,
    changeRate: forecast.changeRate,
    ...partial,
  };
  const all = readAll();
  all.push(row);
  writeAll(all);
  return row;
}

function cryptoRandomId() {
  if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) return crypto.randomUUID();
  return 'id-' + Math.random().toString(36).slice(2);
}

// -------- Auto Snapshot (simple scheduler) ----------
let timer: number | null = null;
let lastConfidence: number | null = null;

export interface AutoSnapshotOptions {
  /** كل قد إيه ناخد سنابشوت (ثواني) */
  intervalSec?: number; // default 60
  /** لو الثقة تغيّرت بأكتر من العتبة ناخد سنابشوت فوراً */
  confidenceDelta?: number; // default 0.05
}

export function startAutoSnapshot(opts: AutoSnapshotOptions = {}) {
  const { intervalSec = 60, confidenceDelta = 0.05 } = opts;
  stopAutoSnapshot();

  // لقطة أولى عند البدء
  const first = generateMetaForecast();
  lastConfidence = first.confidence;
  logSnapshot({ notes: 'auto:start' });

  timer = window.setInterval(() => {
    const now = generateMetaForecast();
    const delta = lastConfidence == null ? 0 : Math.abs(now.confidence - lastConfidence);
    if (delta >= confidenceDelta) {
      logSnapshot({ notes: `auto:delta:${delta.toFixed(3)}` });
      lastConfidence = now.confidence;
    }
  }, intervalSec * 1000);
}

export function stopAutoSnapshot() {
  if (timer != null) {
    window.clearInterval(timer);
    timer = null;
  }
}
