export const dynamic = 'force-dynamic'
export const runtime = 'nodejs'

import { voiceBus, VoiceEventPayload } from '@/lib/voice-bus'

export async function GET(req: Request) {
  const encoder = new TextEncoder()

  const stream = new ReadableStream({
    start(controller) {
      let closed = false
      const safeEnqueue = (chunk: string) => {
        if (closed) return
        try { controller.enqueue(encoder.encode(chunk)) } catch { closed = true }
      }

      // Initial hello — so client sees stream is alive
      safeEnqueue(`: connected ${new Date().toISOString()}\n\n`)

      const onEvent = (evt: VoiceEventPayload) => {
        safeEnqueue(`data: ${JSON.stringify(evt)}\n\n`)
      }
      voiceBus.on('voice', onEvent)

      // Keep-alive ping every 15s so proxies/browsers don't drop the connection
      const pingTimer = setInterval(() => {
        safeEnqueue(`: ping\n\n`)
      }, 15000)

      const abort = () => {
        if (closed) return
        closed = true
        voiceBus.off('voice', onEvent)
        clearInterval(pingTimer)
        try { controller.close() } catch {}
      }

      req.signal.addEventListener('abort', abort)
    },
  })

  return new Response(stream, {
    headers: {
      'Content-Type': 'text/event-stream; charset=utf-8',
      'Cache-Control': 'no-cache, no-transform',
      'Connection': 'keep-alive',
      'X-Accel-Buffering': 'no',
    },
  })
}
