/**
 * Router selection tests.
 *
 * Covered:
 *  - strict model match (Phase 1 has no alias)
 *  - drops offline / saturated backends
 *  - picks lowest busy ratio
 *  - round-robin on tied ratios
 *  - null when no candidate
 *  - first-request-before-warm behaviour (no status row yet)
 */
import { describe, it, expect } from 'vitest';
import { createRouter } from './router.js';
import { createBackendInflightCounter } from './stream-proxy.js';
import type { GatewayBackendConfig } from './config.js';
import type { NodeStatus, BackendStatusRegistry } from '../engine/backend-status-registry.js';

function status(id: string, online: boolean, busy: number, total: number): NodeStatus {
  return {
    nodeId: id,
    workerId: id,
    source: 'direct',
    online,
    busy: busy > 0,
    busySlots: busy,
    totalSlots: total,
    loadedModel: null,
    throughputTps: null,
    lastSeen: new Date().toISOString(),
  };
}

function makeRegistry(rows: NodeStatus[]): Pick<BackendStatusRegistry, 'getAll' | 'noteSubscriberActivity'> {
  return {
    getAll: () => rows.slice(),
    noteSubscriberActivity: () => undefined,
  };
}

function bk(id: string, model: string, maxSlots = 4): GatewayBackendConfig {
  return { id, endpoint: `http://${id}/v1`, model, maxSlots };
}

describe('createRouter.pick', () => {
  it('returns null when model has no configured backend', () => {
    const r = createRouter({
      getBackends: () => [bk('a', 'qwen3:8b')],
      registry: makeRegistry([status('a', true, 0, 4)]),
    });
    expect(r.pick('llama:70b')).toBeNull();
  });

  it('returns null when only candidate is offline', () => {
    const r = createRouter({
      getBackends: () => [bk('a', 'qwen3:8b')],
      registry: makeRegistry([status('a', false, 0, 4)]),
    });
    expect(r.pick('qwen3:8b')).toBeNull();
  });

  it('returns null when all candidates saturated', () => {
    const r = createRouter({
      getBackends: () => [bk('a', 'qwen3:8b'), bk('b', 'qwen3:8b')],
      registry: makeRegistry([
        status('a', true, 4, 4),
        status('b', true, 4, 4),
      ]),
    });
    expect(r.pick('qwen3:8b')).toBeNull();
  });

  it('picks lowest ratio first', () => {
    const r = createRouter({
      getBackends: () => [bk('a', 'qwen3:8b'), bk('b', 'qwen3:8b')],
      registry: makeRegistry([
        status('a', true, 3, 4), // ratio 0.75
        status('b', true, 1, 4), // ratio 0.25 (winner)
      ]),
    });
    expect(r.pick('qwen3:8b')?.id).toBe('b');
  });

  it('round-robins on ties', () => {
    const r = createRouter({
      getBackends: () => [bk('a', 'qwen3:8b'), bk('b', 'qwen3:8b'), bk('c', 'qwen3:8b')],
      registry: makeRegistry([
        status('a', true, 1, 4),
        status('b', true, 1, 4),
        status('c', true, 1, 4),
      ]),
    });
    // Walk through twice the tie group so we see the cursor wrap.
    const picks: string[] = [];
    for (let i = 0; i < 6; i++) picks.push(r.pick('qwen3:8b')!.id);
    // Each backend should appear exactly twice over 6 picks.
    const counts = picks.reduce<Record<string, number>>((acc, id) => {
      acc[id] = (acc[id] ?? 0) + 1;
      return acc;
    }, {});
    expect(counts).toEqual({ a: 2, b: 2, c: 2 });
  });

  it('treats registry-cold backends as idle (avoids startup outage)', () => {
    // Registry has nothing yet — first request still routes.
    const r = createRouter({
      getBackends: () => [bk('a', 'qwen3:8b')],
      registry: makeRegistry([]),
    });
    expect(r.pick('qwen3:8b')?.id).toBe('a');
  });

  it('prefers a warm (probed-alive) backend over a cold (unprobed) one', () => {
    // Before the fix: cold (ratio 0) beats warm (ratio 0.25) because
    // both go in one list and cold sorts first. After: cold is only a
    // fallback when no warm candidate exists.
    const r = createRouter({
      getBackends: () => [bk('warm', 'qwen3:8b'), bk('cold', 'qwen3:8b')],
      registry: makeRegistry([status('warm', true, 1, 4)]),
    });
    // 10 picks — never pick cold while warm has capacity.
    for (let i = 0; i < 10; i++) {
      expect(r.pick('qwen3:8b')?.id).toBe('warm');
    }
  });

  it('falls back to cold round-robin when all candidates are cold', () => {
    // Two unprobed backends — round-robin across them rather than
    // always returning the first by id.
    const r = createRouter({
      getBackends: () => [bk('a', 'qwen3:8b'), bk('b', 'qwen3:8b')],
      registry: makeRegistry([]),
    });
    const picks: string[] = [];
    for (let i = 0; i < 4; i++) picks.push(r.pick('qwen3:8b')!.id);
    const counts = picks.reduce<Record<string, number>>((acc, id) => {
      acc[id] = (acc[id] ?? 0) + 1;
      return acc;
    }, {});
    expect(counts).toEqual({ a: 2, b: 2 });
  });

  it('calls registry.getAll() at most once per pick (no O(N²) lookup)', () => {
    let getAllCalls = 0;
    const rows = [
      status('a', true, 1, 4),
      status('b', true, 2, 4),
      status('c', true, 3, 4),
    ];
    const registry: Pick<BackendStatusRegistry, 'getAll' | 'noteSubscriberActivity'> = {
      getAll: () => { getAllCalls++; return rows.slice(); },
      noteSubscriberActivity: () => undefined,
    };
    const r = createRouter({
      getBackends: () => [
        bk('a', 'qwen3:8b'),
        bk('b', 'qwen3:8b'),
        bk('c', 'qwen3:8b'),
      ],
      registry,
    });
    r.pick('qwen3:8b');
    // Before the fix this would be 3 (one per backend in the loop).
    expect(getAllCalls).toBe(1);
  });

  it('snapshot returns one entry per backend with attached status', () => {
    const r = createRouter({
      getBackends: () => [bk('a', 'qwen3:8b'), bk('b', 'qwen3:14b')],
      registry: makeRegistry([status('a', true, 2, 4)]),
    });
    const snap = r.snapshot();
    expect(snap).toHaveLength(2);
    expect(snap[0]!.status?.online).toBe(true);
    expect(snap[1]!.status).toBeNull();
  });

  it('matches request.model against backend.id (2026-05-21 dogfood regression)', () => {
    // Reproduces the production 503 found during Phase F dogfooding:
    // /v1/models + /health expose `id: backend.id`, the worker echoes
    // that id back as request.model, and the previous router (which
    // filtered only on b.model) couldn't find a match.
    const r = createRouter({
      getBackends: () => [bk('dogfood-gpu-1', 'Qwen3.6-35B-A3B-UD-IQ2_M.gguf')],
      registry: makeRegistry([status('dogfood-gpu-1', true, 0, 4)]),
    });
    expect(r.pick('dogfood-gpu-1')?.id).toBe('dogfood-gpu-1');
  });

  it('still matches request.model against backend.model (legacy callers)', () => {
    const r = createRouter({
      getBackends: () => [bk('dogfood-gpu-1', 'Qwen3.6-35B-A3B-UD-IQ2_M.gguf')],
      registry: makeRegistry([status('dogfood-gpu-1', true, 0, 4)]),
    });
    expect(r.pick('Qwen3.6-35B-A3B-UD-IQ2_M.gguf')?.id).toBe('dogfood-gpu-1');
  });
});

describe('createRouter.pick — live reservation (per-host max_slots enforcement)', () => {
  it('reserves a slot on pick so a maxSlots=1 backend saturates after one pick', () => {
    // Root-cause regression: before the fix, pick() judged saturation
    // only on the 5–30s-stale probe snapshot (busySlots), so a burst of
    // requests arriving inside one probe interval all read busySlots=0
    // and piled onto the same host past max_slots. The reservation makes
    // the second pick see the first request immediately.
    const inflight = createBackendInflightCounter();
    const r = createRouter({
      getBackends: () => [bk('a', 'qwen3:8b', 1)],
      registry: makeRegistry([status('a', true, 0, 1)]), // probe says idle
      inflight,
    });
    expect(r.pick('qwen3:8b')?.id).toBe('a'); // reserves slot 1/1
    expect(inflight.get('a')).toBe(1);
    expect(r.pick('qwen3:8b')).toBeNull(); // saturated by the live reservation, NOT the stale probe
  });

  it('treats live reservations as busy via max(probed, reserved)', () => {
    // total=2, probe still reports 0 busy, but 2 requests are already
    // reserved in-flight → the host is full even though the probe lags.
    const inflight = createBackendInflightCounter();
    inflight.inc('a');
    inflight.inc('a');
    const r = createRouter({
      getBackends: () => [bk('a', 'qwen3:8b', 2)],
      registry: makeRegistry([status('a', true, 0, 2)]),
      inflight,
    });
    expect(r.pick('qwen3:8b')).toBeNull();
  });

  it('spreads a burst across two backends instead of stacking one host', () => {
    // Both probed idle (busy 0/1). Without reservations the stale probe
    // would let the least-busy sort send every request to the same id.
    const inflight = createBackendInflightCounter();
    const r = createRouter({
      getBackends: () => [bk('a', 'qwen3:8b', 1), bk('b', 'qwen3:8b', 1)],
      registry: makeRegistry([status('a', true, 0, 1), status('b', true, 0, 1)]),
      inflight,
    });
    const p1 = r.pick('qwen3:8b')!.id;
    const p2 = r.pick('qwen3:8b')!.id;
    expect(new Set([p1, p2])).toEqual(new Set(['a', 'b'])); // one each
    expect(r.pick('qwen3:8b')).toBeNull(); // both now full
  });

  it('gates registry-cold (unprobed) backends by maxSlots reservations', () => {
    // Boot warm-up window: no probe row yet. The cap must still hold off
    // the live reservation count, not wait for the first probe.
    const inflight = createBackendInflightCounter();
    const r = createRouter({
      getBackends: () => [bk('a', 'qwen3:8b', 1)],
      registry: makeRegistry([]), // cold
      inflight,
    });
    expect(r.pick('qwen3:8b')?.id).toBe('a');
    expect(r.pick('qwen3:8b')).toBeNull();
  });

  it('releasing a reservation (dec) frees the slot for the next pick', () => {
    const inflight = createBackendInflightCounter();
    const r = createRouter({
      getBackends: () => [bk('a', 'qwen3:8b', 1)],
      registry: makeRegistry([status('a', true, 0, 1)]),
      inflight,
    });
    expect(r.pick('qwen3:8b')?.id).toBe('a');
    expect(r.pick('qwen3:8b')).toBeNull();
    inflight.dec('a'); // stream-proxy finally would do this when the request ends
    expect(r.pick('qwen3:8b')?.id).toBe('a');
  });

  it('without an inflight dep, falls back to probe-only behaviour (no reservation)', () => {
    // Legacy/unit callers that do not wire inflight must keep working
    // exactly as before — no hidden reservation side effect.
    const r = createRouter({
      getBackends: () => [bk('a', 'qwen3:8b', 1)],
      registry: makeRegistry([status('a', true, 0, 1)]),
    });
    expect(r.pick('qwen3:8b')?.id).toBe('a');
    expect(r.pick('qwen3:8b')?.id).toBe('a'); // still routes — probe still says idle
  });
});
