import { createElement } from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useTripVoice, type FinalVoiceTranscript } from '@/lib/voice/use-trip-voice'

const livekit = vi.hoisted(() => ({ handlers: new Map<string, (...args: unknown[]) => void>(), microphone: vi.fn(), permit: '', state: '' }))
vi.mock('livekit-client', () => ({
  Room: class {
    localParticipant = { setMicrophoneEnabled: livekit.microphone }
    remoteParticipants = new Map([['agent', { attributes: { 'workspace.permit_id': livekit.permit, 'workspace.state_code': livekit.state } }]])
    on(event: string, handler: (...args: unknown[]) => void) { livekit.handlers.set(event, handler); return this }
    off(event: string) { livekit.handlers.delete(event); return this }
    async connect() {}
    disconnect() {}
  },
  RoomEvent: { TranscriptionReceived: 'transcript', DataReceived: 'data', TrackSubscribed: 'subscribed', TrackUnsubscribed: 'unsubscribed', Disconnected: 'disconnected', ParticipantAttributesChanged: 'attributes', ParticipantConnected: 'participant-connected' },
  Track: { Kind: { Audio: 'audio' } },
}))

beforeEach(() => {
  livekit.handlers.clear()
  livekit.microphone.mockReset().mockResolvedValue(undefined)
  livekit.permit = ''; livekit.state = ''
  vi.stubGlobal('fetch', vi.fn().mockResolvedValue(Response.json({ url: 'wss://voice.test', token: 'token' })))
})
afterEach(() => vi.unstubAllGlobals())

async function connect(selection: { permitId?: string; stateCode?: string } = {}) {
  const transcripts: FinalVoiceTranscript[] = []
  const evidence: string[] = []
  let voice: ReturnType<typeof useTripVoice> | undefined
  function TestVoice() {
    voice = useTripVoice({ tripId: 'trip', language: 'en', enabled: true,
      onTranscript: transcript => transcripts.push(transcript), onEvidence: id => evidence.push(id), ...selection })
    return null
  }
  renderToStaticMarkup(createElement(TestVoice))
  await voice!.start()
  return { transcripts, evidence, voice: voice! }
}

describe('LiveKit chat transcript regression', () => {
  it('ignores late transcripts after stopping the previous room', async () => {
    const { transcripts, voice } = await connect()
    const oldTranscript = livekit.handlers.get('transcript')!
    await voice.stop()
    oldTranscript([{ id: 'late', text: 'Old permit reply', final: true }], { isLocal: false })
    expect(transcripts).toEqual([])
  })
  it('sends the selection to voice and stamps final transcripts with the confirmed permit', async () => {
    livekit.permit = 'selected-permit'; livekit.state = 'LA'
    const { transcripts } = await connect({ permitId: 'selected-permit', stateCode: 'LA' })
    expect(JSON.parse(vi.mocked(fetch).mock.calls[0][1]!.body as string)).toMatchObject({ permit_id: 'selected-permit', state_code: 'LA' })
    expect(livekit.microphone).toHaveBeenCalledWith(true)
    livekit.handlers.get('transcript')!([{ id: 'a', text: 'Louisiana answer', final: true }], { isLocal: false })
    expect(transcripts[0]).toMatchObject({ role: 'assistant', stateCode: 'LA', permitId: 'selected-permit' })
  })
  it('delivers both questions and answers in speech order without any metadata endpoint', async () => {
    const { transcripts } = await connect()
    const emit = livekit.handlers.get('transcript')!
    emit([{ id: 'q1', text: 'Can I travel?', final: true }], { isLocal: true })
    emit([{ id: 'a1', text: 'Daylight only.', final: true }], { isLocal: false })
    emit([{ id: 'q2', text: 'What about Sunday?', final: true }], { isLocal: true })
    emit([{ id: 'a2', text: 'Check the permit.', final: true }], { isLocal: false })
    expect(transcripts.map(item => [item.role, item.content])).toEqual([
      ['user', 'Can I travel?'], ['assistant', 'Daylight only.'],
      ['user', 'What about Sunday?'], ['assistant', 'Check the permit.'],
    ])
  })
  it('deduplicates repeated final segments and ignores partial or empty speech', async () => {
    const { transcripts } = await connect()
    const emit = livekit.handlers.get('transcript')!
    emit([{ id: 'a1', text: 'Partial', final: false }, { id: 'empty', text: '', final: true }], { isLocal: false })
    emit([{ id: 'a1', text: 'Final answer.', final: true }], { isLocal: false })
    emit([{ id: 'a1', text: 'Final answer.', final: true }], { isLocal: false })
    expect(transcripts).toEqual([{ role: 'assistant', content: 'Final answer.', segmentId: 'a1' }])
  })
  it('uses metadata only for optional evidence and never creates an empty or duplicate answer', async () => {
    const { transcripts, evidence } = await connect()
    const id = '22222222-2222-4222-8222-222222222222'
    const payload = new TextEncoder().encode(JSON.stringify({ type: 'logistics-bot-metadata', metadata: { backend_message_id: id } }))
    const emit = livekit.handlers.get('data')!
    emit(payload, { isLocal: false }, undefined, 'logistics.metadata')
    emit(payload, { isLocal: false }, undefined, 'logistics.metadata')
    expect(evidence).toEqual([id])
    expect(transcripts).toEqual([])
    livekit.handlers.get('transcript')!([{ id: 'a', text: 'Real spoken answer.', final: true }], { isLocal: false })
    expect(transcripts[0].content).toBe('Real spoken answer.')
  })
})
