import { describe, it, expect, beforeEach } from 'vitest';
import fs from 'node:fs';
import { Phase6Config } from '../../config/phase6.config';
import { toSnapshot } from '../../lib/memory/snapshot';
import { LongTermMemory } from '../../lib/memory/long_term_memory';
import { FeedbackReport } from '../../types/phase5';

function makeReport(iteration: number, a: number, b: number): FeedbackReport {
  return {
    timestamp: new Date(Date.now() + iteration * 1000).toISOString(),
    iteration,
    policies: [
      { policyId: 'A', score: a, failures: Math.round((1 - a) * 5), attempts: 5 },
      { policyId: 'B', score: b, failures: Math.round((1 - b) * 5), attempts: 5 },
    ],
  };
}

describe('Phase 6.1 — LongTermMemory', () => {
  beforeEach(() => {
    if (fs.existsSync(Phase6Config.storagePath)) fs.unlinkSync(Phase6Config.storagePath);
  });

  it('accumulates snapshots and computes correct metrics', () => {
    const reports = [
      makeReport(1, 0.4, 0.55),
      makeReport(2, 0.42, 0.57),
      makeReport(3, 0.45, 0.59),
      makeReport(4, 0.48, 0.6),
    ];
    for (const r of reports) {
      LongTermMemory.appendSnapshot(toSnapshot(r));
    }
    const state = LongTermMemory.getState();
    expect(state.snapshots.length).toBe(4);
    expect(state.metrics).toBeTruthy();
    expect(state.metrics!.adaptationRate).toBeGreaterThan(0);
    expect(state.metrics!.stability).toBeLessThan(0.05);
  });
});
