/**
 * PERF3 evidence: pump() rescans the whole items array per queue event
 * (filter + filter/reverse/slice + Set + map). The audit deferred a
 * count+pointer rewrite as risk > reward on a bounded list — this benchmark
 * pins that judgment with numbers at and beyond realistic queue sizes
 * (a large channel enqueue is a few thousand items; events arrive a few times
 * per second while downloads run).
 *
 * The measured pipeline below replicates pump()'s exact array operations on
 * the same item shape (the real pump also spawns downloads, which would drown
 * the scan in noise); the generous assertion doubles as a regression tripwire.
 */
import { describe, it, expect } from 'vitest'
import type { DownloadItem } from '../src/renderer/src/store/downloadTypes'

function makeItems(n: number): DownloadItem[] {
  const statuses: DownloadItem['status'][] = ['completed', 'queued', 'downloading', 'error']
  return Array.from({ length: n }, (_, i) => ({
    id: `i${i}`,
    url: `https://example.com/v/${i}`,
    title: `Video ${i}`,
    kind: 'video',
    quality: '1080p',
    status: statuses[i % statuses.length]!,
    progress: 0
  }))
}

/** pump()'s scan/promote pipeline, byte-for-byte the same array operations. */
function pumpScan(items: DownloadItem[], maxConcurrent: number): number {
  const running = items.filter((i) => i.status === 'downloading').length
  const slots = maxConcurrent - running
  if (slots <= 0) return 0
  const toStart = items
    .filter((i) => i.status === 'queued')
    .reverse()
    .slice(0, slots)
  if (toStart.length === 0) return 0
  const ids = new Set(toStart.map((i) => i.id))
  const next = items.map((i) => (ids.has(i.id) ? { ...i, status: 'downloading' as const } : i))
  return next.length
}

function bench(items: DownloadItem[], maxConcurrent: number, iterations: number): number {
  // Warm up JIT + caches.
  for (let i = 0; i < 20; i++) pumpScan(items, maxConcurrent)
  const times: number[] = []
  for (let i = 0; i < iterations; i++) {
    const t0 = performance.now()
    pumpScan(items, maxConcurrent)
    times.push(performance.now() - t0)
  }
  times.sort((a, b) => a - b)
  return times[Math.floor(times.length / 2)]!
}

describe('pump() cost at scale (PERF3)', () => {
  it('a full scan+promote over 5,000 items is well under a millisecond-scale budget', () => {
    const median = bench(makeItems(5_000), 3 + 1_250, 50) // slots open → full pipeline

    console.log(`pump pipeline @5k items: median ${median.toFixed(3)} ms`)
    expect(median).toBeLessThan(5)
  })

  it('a full scan+promote over 20,000 items stays inside a 5 ms budget', () => {
    const median = bench(makeItems(20_000), 3 + 5_000, 50)

    console.log(`pump pipeline @20k items: median ${median.toFixed(3)} ms`)
    expect(median).toBeLessThan(5)
  })

  it('the no-free-slot fast path (the per-progress-event case) is trivially cheap', () => {
    const median = bench(makeItems(20_000), 1, 100) // running >= cap → early return

    console.log(`pump no-slot path @20k items: median ${median.toFixed(3)} ms`)
    expect(median).toBeLessThan(2)
  })
})
