import { afterEach, describe, expect, it, vi } from 'vitest';
import { normalizeSummary, quarantineImplementation, restoreImplementation } from './api';

afterEach(() => {
  vi.unstubAllGlobals();
  window.sessionStorage.clear();
});

describe('FastAPI dashboard adapter', () => {
  it('converts backend fractional rates and status data into presentation values', () => {
    const result = normalizeSummary({
      release: { application: 'zipdiv', version: '1.2.3', repository_url: 'https://github.com/example/zipdiv', artifact_url: 'https://example.test/zipdiv' },
      clients: 12,
      spec_functions: 2,
      implementations_per_function: [2, 3],
      theoretical_compositions: 6,
      observed_compositions: 5,
      latest_execution_at: '2026-08-28T12:00:01Z',
      telemetry_events: 4,
      executions: 100,
      failures: 8,
      failure_rate: 0.08,
      active_distribution: [{ spec_function: 'validate_crc', implementation_id: 'crc_fold', clients: 7 }],
      implementation_stats: [{
        id: 'crc_fold', name: 'fold CRC', status: 'active', spec_function: 'validate_crc',
        clients_observed: 7, executions: 50, failures: 6, failure_rate: 0.12,
        alternative_failure_rate: 0.03, relative_risk: 4, infinite_relative_risk: false, experimental: true,
        source_url: 'https://github.com/example/zipdiv/blob/abc/src/variants.rs',
      }, {
        id: 'crc_safe', name: 'safe CRC', status: 'active', spec_function: 'validate_crc',
        clients_observed: 5, executions: 60, failures: 1, failure_rate: 0.016,
        alternative_failure_rate: 0.08, relative_risk: 0.2, infinite_relative_risk: false,
      }],
      pairwise_interactions: [], quarantined: [], recompositions: [], quarantine_effects: [],
      quarantine_sequence: [{ implementation_id: null, executions: 100, healthy_rate: 0.92 }], failure_timeline: [],
    }, [{
      id: 1, event_type: 'integrity_failure', created_at: '2026-08-28T12:00:00Z',
      client_id: 'pc_abcdefghijklmnop', implementation_id: 'crc_fold', spec_function: 'validate_crc',
      message_code: 'crc_mismatch', recent_calls: [],
    }]);

    expect(result.summary.populationFailureRate).toBe(8);
    expect(result.summary.implementations).toBe(5);
    expect(result.summary.activeCompositions).toBe(5);
    expect(result.generatedAt).toBe('2026-08-28T12:00:01Z');
    expect(result.release).toMatchObject({ name: 'zipdiv', version: '1.2.3', repositoryUrl: 'https://github.com/example/zipdiv' });
    expect(result.implementations[0]).toMatchObject({ failureRate: 12, relativeRisk: 4, status: 'watch', variant: 'CF', variantName: 'crc_fold', experimental: true, sourceUrl: 'https://github.com/example/zipdiv/blob/abc/src/variants.rs' });
    expect(result.implementations.map((item) => item.id)).toEqual(['crc_fold', 'crc_safe']);
    expect(result.telemetry[0]).toMatchObject({ severity: 'critical', message: 'crc_mismatch' });
  });

  it('scopes quarantine mutations to the selected release', async () => {
    window.sessionStorage.setItem('polyform-admin-token', 'test-secret');
    const fetchMock = vi.fn().mockResolvedValue({ ok: true });
    vi.stubGlobal('fetch', fetchMock);
    await quarantineImplementation('validate_crc.chunked', 7, 'high relative risk');
    expect(fetchMock).toHaveBeenCalledWith(
      '/api/v1/implementations/validate_crc.chunked/status?release_id=7',
      expect.objectContaining({ method: 'PUT', headers: expect.objectContaining({ 'X-Polyform-Admin-Token': 'test-secret' }) }),
    );
  });

  it('can restore a quarantined implementation for future assignments', async () => {
    window.sessionStorage.setItem('polyform-admin-token', 'test-secret');
    const fetchMock = vi.fn().mockResolvedValue({ ok: true });
    vi.stubGlobal('fetch', fetchMock);
    await restoreImplementation('validate_crc.chunked', 7, 'operator review');
    expect(fetchMock).toHaveBeenCalledWith(
      '/api/v1/implementations/validate_crc.chunked/status?release_id=7',
      expect.objectContaining({ method: 'PUT', body: JSON.stringify({ status: 'active', reason: 'operator review' }) }),
    );
  });

  it('uses post-quarantine executions for the live healthy-execution rate', () => {
    const result = normalizeSummary({
      clients: 20, spec_functions: 1, implementations_per_function: [5],
      theoretical_compositions: 5, observed_compositions: 5,
      telemetry_events: 3, executions: 120, failures: 30, failure_rate: 0.25,
      active_distribution: [], implementation_stats: [], pairwise_interactions: [], failure_timeline: [],
      quarantined: [{ id: 'bad', name: 'bad', status_reason: 'test' }],
      recompositions: [{ implementation_id: 'bad', affected_clients: 4 }],
      quarantine_effects: [{
        implementation_id: 'bad', before_failure_rate: 0.25,
        after_failure_rate: 0.05, after_executions: 40,
      }],
      quarantine_sequence: [
        { implementation_id: null, executions: 80, healthy_rate: 0.75 },
        { implementation_id: 'earlier_bad', executions: 0, healthy_rate: null },
        { implementation_id: 'bad', executions: 40, healthy_rate: 0.95 },
      ],
    }, []);

    expect(result.summary.populationFailureRate).toBe(5);
    expect(result.summary.previousFailureRate).toBe(25);
    expect(result.quarantines[0].afterExecutions).toBe(40);
    expect(result.healthSequence.map((stage) => stage.label)).toEqual(['Baseline', 'After EB', 'After BAD']);
  });
});
