/**
 * Per-engine quality from run history (§2) — pure unit tests.
 */

import { describe, expect, it } from 'vitest';
import { computeEngineQuality, isCostRoutingEnabled } from './engine-stats.js';
import type { FleetRunDoc } from './types.js';

let seq = 0;
function run(over: Partial<FleetRunDoc> & { engine: string }): FleetRunDoc {
  seq += 1;
  return {
    id: `r${seq}`,
    productId: 'lysnrai',
    jobId: `j${seq}`,
    attempt: 1,
    startedAt: '2026-06-01T00:00:00.000Z',
    insights: {},
    ...over,
  } as FleetRunDoc;
}

/** A run with a cost and a duration (ms) on a given engine. */
function costed(engine: string, costUsd: number, durationMs: number): FleetRunDoc {
  const start = '2026-06-01T00:00:00.000Z';
  const end = new Date(Date.parse(start) + durationMs).toISOString();
  return run({ engine, startedAt: start, endedAt: end, insights: { costUsd } });
}

describe('computeEngineQuality §2', () => {
  it('cheapest + fastest engine anchors quality at 1; pricier/slower decays', () => {
    const { lookup, byEngine } = computeEngineQuality([
      costed('devin', 1, 1000),
      costed('codex', 4, 4000),
    ]);
    expect(lookup('devin')).toBeCloseTo(1);
    // codex: costScore 1/4, durScore 1000/4000 ⇒ (0.25 + 0.25)/2 = 0.25
    expect(lookup('codex')).toBeCloseTo(0.25);
    expect(byEngine.get('codex')?.avgCostUsd).toBe(4);
    expect(byEngine.get('codex')?.samples).toBe(1);
  });

  it('averages multiple runs per engine', () => {
    const { byEngine } = computeEngineQuality([costed('devin', 2, 1000), costed('devin', 4, 3000)]);
    expect(byEngine.get('devin')?.avgCostUsd).toBe(3);
    expect(byEngine.get('devin')?.avgDurationMs).toBe(2000);
  });

  it('unknown / no-history engines are neutral (1) — never penalised', () => {
    const { lookup } = computeEngineQuality([costed('devin', 5, 5000)]);
    expect(lookup('claude')).toBe(1);
    expect(lookup(undefined)).toBe(1);
  });

  it('a single engine with data scores 1 (term is inert with no peer to compare)', () => {
    const { lookup } = computeEngineQuality([costed('devin', 9, 9000)]);
    expect(lookup('devin')).toBeCloseTo(1);
  });

  it('uses whichever signal is present (cost-only / duration-only)', () => {
    const { lookup } = computeEngineQuality([
      run({ engine: 'devin', insights: { costUsd: 1 } }), // cost only, no endedAt
      run({ engine: 'codex', insights: { costUsd: 5 } }),
    ]);
    expect(lookup('devin')).toBeCloseTo(1);
    expect(lookup('codex')).toBeCloseTo(0.2);
  });

  it('ignores runs with no engine, "unknown" engine, or no usable signal', () => {
    const { byEngine } = computeEngineQuality([
      run({ engine: 'unknown', insights: { costUsd: 3 } }),
      run({ engine: 'devin', insights: {} }), // no cost, no end
      costed('codex', 2, 2000),
    ]);
    expect(byEngine.has('unknown')).toBe(false);
    expect(byEngine.has('devin')).toBe(false);
    expect(byEngine.has('codex')).toBe(true);
  });

  it('empty history ⇒ everything neutral', () => {
    const { lookup, byEngine } = computeEngineQuality([]);
    expect(byEngine.size).toBe(0);
    expect(lookup('devin')).toBe(1);
  });
});

describe('isCostRoutingEnabled §2', () => {
  it('defaults OFF and honors truthy env values', () => {
    const prev = process.env.FLEET_COST_ROUTING;
    try {
      delete process.env.FLEET_COST_ROUTING;
      expect(isCostRoutingEnabled()).toBe(false);
      process.env.FLEET_COST_ROUTING = 'on';
      expect(isCostRoutingEnabled()).toBe(true);
      process.env.FLEET_COST_ROUTING = '0';
      expect(isCostRoutingEnabled()).toBe(false);
    } finally {
      if (prev === undefined) delete process.env.FLEET_COST_ROUTING;
      else process.env.FLEET_COST_ROUTING = prev;
    }
  });
});
