import { NextRequest, NextResponse } from 'next/server'
import { progressTracker } from '../../../../../lib/progress-tracker'

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ sessionId: string }> }
) {
  const { sessionId } = await params

  // Create a readable stream for Server-Sent Events
  const encoder = new TextEncoder()
  
  const stream = new ReadableStream({
    start(controller) {
      // Send initial progress if session exists
      const initialProgress = progressTracker.getProgress(sessionId)
      if (initialProgress) {
        const data = `data: ${JSON.stringify(initialProgress)}\n\n`
        controller.enqueue(encoder.encode(data))
      }

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

      // Listen for completion
      const completeHandler = () => {
        const data = `data: ${JSON.stringify({ type: 'complete' })}\n\n`
        controller.enqueue(encoder.encode(data))
        controller.close()
      }

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

      // Cleanup on stream close
      request.signal.addEventListener('abort', () => {
        progressTracker.off(`progress:${sessionId}`, progressHandler)
        progressTracker.off(`progress:${sessionId}:complete`, completeHandler)
        controller.close()
      })
    }
  })

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