import { describe, it, expect } from 'vitest'
import { __testing } from '../commands/bestof.js'

const { parseArgs, buildPrompt } = __testing

describe('bestof parseArgs', () => {
  it('accepts a valid N + task', () => {
    const out = parseArgs('3 refactor the auth middleware')
    expect(out).toEqual({ n: 3, task: 'refactor the auth middleware' })
  })

  it('trims extra whitespace', () => {
    const out = parseArgs('  4   implement  feature X  ')
    expect(out).toEqual({ n: 4, task: 'implement  feature X' })
  })

  it('rejects empty input', () => {
    expect(parseArgs('')).toEqual({ error: expect.stringContaining('Usage') })
    expect(parseArgs('   ')).toEqual({ error: expect.stringContaining('Usage') })
  })

  it('rejects missing task', () => {
    expect(parseArgs('3')).toEqual({ error: expect.stringContaining('Usage') })
  })

  it('rejects non-numeric N', () => {
    expect(parseArgs('three tasks')).toEqual({ error: expect.stringContaining('Usage') })
  })

  it('rejects N below 2', () => {
    expect(parseArgs('1 just do it')).toEqual({
      error: expect.stringMatching(/between 2 and 5/),
    })
    expect(parseArgs('0 just do it')).toEqual({
      error: expect.stringMatching(/between 2 and 5/),
    })
  })

  it('rejects N above 5', () => {
    expect(parseArgs('6 too many')).toEqual({
      error: expect.stringMatching(/between 2 and 5/),
    })
    expect(parseArgs('99 nope')).toEqual({
      error: expect.stringMatching(/between 2 and 5/),
    })
  })

  it('handles multiline task text', () => {
    const out = parseArgs('2 implement feature\nwith details\non multiple lines')
    expect(out).toEqual({
      n: 2,
      task: 'implement feature\nwith details\non multiple lines',
    })
  })
})

describe('bestof buildPrompt', () => {
  it('embeds the task verbatim', () => {
    const prompt = buildPrompt(3, 'add an LRU cache to the rate limiter')
    expect(prompt).toContain('add an LRU cache to the rate limiter')
  })

  it('embeds N in the instructions', () => {
    const prompt = buildPrompt(4, 'test')
    expect(prompt).toContain('best-of-4')
    expect(prompt).toMatch(/\b4 parallel\b/i)
  })

  it('requires the subagents to plan, not apply', () => {
    const prompt = buildPrompt(3, 'anything')
    expect(prompt).toMatch(/do not apply|plan only/i)
    expect(prompt).toMatch(/Do NOT edit files/i)
  })

  it('instructs the primary to pick a winner with justification', () => {
    const prompt = buildPrompt(3, 'anything')
    expect(prompt).toMatch(/winner/i)
    expect(prompt).toMatch(/comparison table/i)
  })

  it('gates application behind a user confirmation', () => {
    const prompt = buildPrompt(3, 'anything')
    expect(prompt).toMatch(/Apply \[winner\]/)
  })
})
