import { describe, it, expect, vi, beforeEach } from 'vitest';
import { runFeedbackCycle } from '../../lib/feedback/runner';
import { getMetrics, resetMetrics } from '../../lib/feedback/metrics';
import type { Signal } from '../../lib/feedback/types';

describe('🧠 Feedback & Evaluation Integration Tests — Phase 6.1 Aligned', () => {
  beforeEach(() => resetMetrics?.());

  it('✅ normal signals stay NORMAL', async () => {
    const signals: Signal[] = [{ kind: 'LOAD', value: 10 }];
    const result = await runFeedbackCycle(signals);
    expect(result.evaln.severity).toBe('NORMAL');
  });

  it('⚠️ detects WARNING', async () => {
    const signals: Signal[] = [
      { kind: 'LOAD', value: 55 },
      { kind: 'LATENCY', value: 45 },
    ];
    const result = await runFeedbackCycle(signals);
    expect(['WARNING', 'CRITICAL']).toContain(result.evaln.severity);
  });

  it('🚨 triggers rollback when critical error', async () => {
    const signals: Signal[] = [
      { kind: 'ERROR', value: 90 },
      { kind: 'LATENCY', value: 85 },
    ];
    const result = await runFeedbackCycle(signals);
    expect(result.evaln.severity).toBe('CRITICAL');
  });

  it('💣 handles failed action gracefully', async () => {
    const mod = await vi.importActual<any>('../../lib/feedback/actions');
    const spy = vi.spyOn(mod, 'execute').mockImplementation(async () => {
      throw new Error('forced failure');
    });

    const signals: Signal[] = [
      { kind: 'ERROR', value: 70 },
      { kind: 'LATENCY', value: 55 },
    ];

    const result = await runFeedbackCycle(signals);

    // ✅ ما حصلش crash، النظام راجع تقييم عادي
    expect(result).toHaveProperty('evaln');
    expect(result.evaln.severity).toBeDefined();
    // 🚫 الـ runner بيتعامل مع rollback كنجاح منطقي
    expect(result.ok ?? result.result?.ok ?? true).toBe(true);

    spy.mockRestore();
  });

  it('🧩 records feedback cycles indirectly through metrics', async () => {
    const signals: Signal[] = [{ kind: 'LATENCY', value: 10 }];
    await runFeedbackCycle(signals);
    const m = getMetrics();
    expect(m.totalCycles).toBeGreaterThan(0);
  });

  it('🧮 diverse outcomes across patterns', async () => {
    const patterns: Signal[][] = [
      [{ kind: 'LOAD', value: 10 }],
      [{ kind: 'LATENCY', value: 55 }],
      [{ kind: 'ERROR', value: 90 }],
    ];
    const severities = new Set<string>();
    for (let i = 0; i < 30; i++) {
      const res = await runFeedbackCycle(patterns[i % 3]);
      severities.add(res.evaln.severity);
    }
    expect(severities.size).toBeGreaterThanOrEqual(2);
    expect(getMetrics().totalCycles).toBeGreaterThan(10);
  });
});
