import { describe, it, expect, beforeEach } from 'vitest';
import fs from 'node:fs';
import { Phase6Config } from '../../config/phase6.config';
import { PolicyConfig } from '../../config/policy.config';
import { LongTermMemory as MemoryKernel } from '../../lib/memory/long_term_memory';
import { createSnapshot } from '../../lib/memory/snapshot_model'; // ✅ أضف السطر ده هنا 👈

import { loadRegistry, saveRegistry } from '../../lib/policy/registry';
import { updateAllPolicies } from '../../lib/policy/tracker_engine';

function resetFiles() {
  if (fs.existsSync(Phase6Config.storagePath)) fs.unlinkSync(Phase6Config.storagePath);
  if (fs.existsSync(PolicyConfig.registryPath)) fs.unlinkSync(PolicyConfig.registryPath);
  if (fs.existsSync(PolicyConfig.historyPath)) fs.unlinkSync(PolicyConfig.historyPath);
}

describe('Phase 6.2 — Policy Tracker', () => {
  beforeEach(() => resetFiles());

  it('updates policy weights and logs history', () => {
    // Create synthetic snapshots
    for (let i = 1; i <= 5; i++) {
      MemoryKernel.appendSnapshot(
        createSnapshot(i, {
          policies: [
            { policyId: 'POL-FEED-01', score: 0.4 + i * 0.05, failures: 2, attempts: 10 },
            { policyId: 'POL-STAB-02', score: 0.35 + i * 0.03, failures: 3, attempts: 10 },
          ],
        })
      );
    }

    saveRegistry([
      {
        policyId: 'POL-FEED-01',
        name: 'Feedback Depth',
        description: 'Depth of reflective analysis',
        weight: 0.5,
        status: 'active',
        trend: '→',
        lastUpdate: new Date().toISOString(),
        _lastDelta: 0,
      },
      {
        policyId: 'POL-STAB-02',
        name: 'Stability Bias',
        description: 'Balance between speed and stability',
        weight: 0.6,
        status: 'active',
        trend: '→',
        lastUpdate: new Date().toISOString(),
        _lastDelta: 0,
      },
    ]);

    const before = loadRegistry();
    const result = updateAllPolicies();
    const after = result.registry;

    expect(after.length).toBe(2);
    const w1Before = before[0].weight;
    const w1After = after[0].weight;
    expect(w1After).toBeGreaterThanOrEqual(w1Before);
    expect(['↑', '↓', '→']).toContain(after[0].trend);
  });
});
