// tests/phase8.97/consistency_check.spec.ts
import { describe, it, expect, beforeEach } from 'vitest';
import { verifyCognitiveConsistency } from '@/lib/evolution/consistency.check';
import { upsertEvolutionReport } from '@/lib/telemetry/evolution.telemetry';

beforeEach(() => {
  localStorage.clear();
  const now = new Date().toISOString();
  // Seed report
  upsertEvolutionReport({
    lastUpdated: now,
    lastContext: { device: 'desktop', perfMode: false },
    metrics: { stability: 0.74, adaptationRate: 0.022 },
  });

  // Seed history
  const history = [
    {
      ts: new Date(Date.now() - 86400000 * 2).toISOString(),
      device: 'desktop',
      perfMode: false,
      metrics: { stability: 0.72, adaptationRate: 0.021 },
    },
    {
      ts: now,
      device: 'desktop',
      perfMode: false,
      metrics: { stability: 0.74, adaptationRate: 0.022 },
    },
  ];
  localStorage.setItem('EVOLUTION_HISTORY', JSON.stringify(history));
});

describe('🧩 Phase 8.97 — Cognitive Consistency Verification', () => {
  it('computes consistency index and updates Evolution Report', () => {
    const result = verifyCognitiveConsistency();
    expect(result).toHaveProperty('consistencyIndex');
    expect(result).toHaveProperty('status');
    expect(['stable', 'partial', 'inconsistent']).toContain(result.status);
  });

  it('detects chronological consistency', () => {
    const history = JSON.parse(localStorage.getItem('EVOLUTION_HISTORY')!);
    // أعد التاريخ الثاني بشكل معكوس لاختبار الخطأ الزمني
    history.reverse();
    localStorage.setItem('EVOLUTION_HISTORY', JSON.stringify(history));

    const result = verifyCognitiveConsistency();
    expect(result.consistencyIndex).toBeLessThan(1);
  });

  it('handles empty history gracefully', () => {
    localStorage.removeItem('EVOLUTION_HISTORY');
    const result = verifyCognitiveConsistency();
    expect(result.status).toBe('empty_history');
  });
});
