// lib/telemetry/evolution.telemetry.ts
import { predictNext } from '../evolution/predictive-engine';
import { buildTimeline } from '../evolution/timeline';
type EvolutionLogEntry = {
  ts: string;
  event: string;
  extra?: Record<string, any> | null;
};

type EvolutionReport = {
  lastUpdated?: string;
  phase?: number;
  lastContext?: {
    device?: string;
    perfMode?: boolean;
    animations?: string;
    density?: string;
    confidence?: number;
  };
  metrics?: Record<string, number>;
  history?: Array<Record<string, any>>;
};

/** يسجّل حدث تطوّر عام */
export function recordEvolutionEvent(event: string, extra?: Record<string, any>) {
  const entry: EvolutionLogEntry = {
    ts: new Date().toISOString(),
    event,
    extra: extra ?? null,
  };
  try {
    const key = 'EVOLUTION_LOG';
    const prev = JSON.parse(localStorage.getItem(key) || '[]');
    prev.push(entry);
    localStorage.setItem(key, JSON.stringify(prev.slice(-200))); // آخر 200 حدث
  } catch {}
}

/** قراءة تقرير التطوّر الحالي (إن وجد) */
export function readEvolutionReport(): EvolutionReport {
  try {
    const raw = localStorage.getItem('EVOLUTION_REPORT');
    return raw ? (JSON.parse(raw) as EvolutionReport) : {};
  } catch {
    return {};
  }
}

/** دمج/تحديث تقرير التطوّر الحالي (upsert) */
export function upsertEvolutionReport(patch: Partial<EvolutionReport>) {
  const current = readEvolutionReport();
  const next: EvolutionReport = deepMerge(current, patch);
  try {
    localStorage.setItem('EVOLUTION_REPORT', JSON.stringify(next));
  } catch {}
  return next;
}

export function recordPrediction() {
  const tl = buildTimeline();
  const pred = predictNext(tl);
  if (!pred) return;

  const reportKey = 'Evolution_Report';
  const report = JSON.parse(localStorage.getItem(reportKey) || '{}');
  report.prediction = pred;
  localStorage.setItem(reportKey, JSON.stringify(report));
  console.log('🧠 [Predictive] Forecast recorded:', pred);
}

/** دمج بسيط للـ objects */
function deepMerge<T>(base: T, patch?: Partial<T>): T {
  if (!patch) return base;
  const out: any = Array.isArray(base) ? [...(base as any)] : { ...(base as any) };
  for (const k of Object.keys(patch)) {
    const v = (patch as any)[k];
    if (v && typeof v === 'object' && !Array.isArray(v))
      out[k] = deepMerge((out as any)[k] ?? {}, v);
    else out[k] = v;
  }
  return out;
}
