/**
 * WebSocket route for real-time agent communication
 */

import { NextRequest } from "next/server"
import { getCloudflareContext } from "@opennextjs/cloudflare"

// Get Durable Object stub
function getDurableObjectStub(runId: string, env: any) {
  const id = env.BANDIT_AGENT.idFromName(runId)
  return env.BANDIT_AGENT.get(id)
}

/**
 * GET /api/agent/[runId]/ws
 * Upgrade to WebSocket connection
 */
export async function GET(
  request: NextRequest,
  { params }: { params: { runId: string } }
) {
  const runId = params.runId
  console.log('[WS Route] Incoming request for runId:', runId)
  console.log('[WS Route] Headers:', Object.fromEntries(request.headers.entries()))
  
  const { env } = await getCloudflareContext()

  if (!env?.BANDIT_AGENT) {
    console.error('[WS Route] Durable Object binding not found')
    return new Response("Durable Object binding not found", { status: 500 })
  }

  try {
    // Forward WebSocket upgrade to Durable Object
    const stub = getDurableObjectStub(runId, env)
    
    // Create a new request with WebSocket upgrade headers
    const upgradeHeader = request.headers.get('Upgrade')
    console.log('[WS Route] Upgrade header:', upgradeHeader)
    
    if (!upgradeHeader || upgradeHeader !== 'websocket') {
      console.log('[WS Route] Invalid upgrade header, returning 426')
      return new Response('Expected Upgrade: websocket', { status: 426 })
    }

    console.log('[WS Route] Forwarding to DO...')
    // Forward the request to DO
    const response = await stub.fetch(request)
    console.log('[WS Route] DO response status:', response.status)
    return response
  } catch (error) {
    console.error('[WS Route] WebSocket upgrade error:', error)
    return new Response(
      error instanceof Error ? error.message : 'Unknown error',
      { status: 500 }
    )
  }
}

