import { progressTracker } from '../../../lib/progress-tracker'

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url)
  const sessionId = searchParams.get('sessionId')

  if (!sessionId) {
    return new Response('Session ID required', { status: 400 })
  }

  const stream = new ReadableStream({
    start(controller) {
      // Send initial progress if session exists
      const currentProgress = progressTracker.getProgress(sessionId)
      if (currentProgress) {
        const data = `data: ${JSON.stringify(currentProgress)}\n\n`
        controller.enqueue(new TextEncoder().encode(data))
      }

      // Listen for progress updates
      const progressHandler = (progress: any) => {
        const data = `data: ${JSON.stringify(progress)}\n\n`
        controller.enqueue(new TextEncoder().encode(data))
      }

      const completeHandler = () => {
        const data = `data: ${JSON.stringify({ type: 'complete' })}\n\n`
        controller.enqueue(new TextEncoder().encode(data))
        controller.close()
      }

      progressTracker.on(`progress:${sessionId}`, progressHandler)
      progressTracker.on(`progress:${sessionId}:complete`, completeHandler)

      // Cleanup on close
      return () => {
        progressTracker.off(`progress:${sessionId}`, progressHandler)
        progressTracker.off(`progress:${sessionId}:complete`, completeHandler)
      }
    }
  })

  return new Response(stream, {
    headers: {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Headers': 'Cache-Control'
    }
  })
}
