/**
 * POST /api/agent/[runId]/start - Start a new agent run
 */

import { NextRequest, NextResponse } from "next/server"
import { getCloudflareContext } from "@opennextjs/cloudflare"
import type { RunConfig } from "@/lib/agents/bandit-state"

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

export async function POST(
  request: NextRequest,
  { params }: { params: { runId: string } }
) {
  const runId = params.runId
  const body = await request.json()

  // Get cloudflare env from OpenNext context
  const { env } = await getCloudflareContext()

  if (!env?.BANDIT_AGENT) {
    return NextResponse.json(
      { error: "Durable Object binding not found" },
      { status: 500 }
    )
  }

  try {
    const stub = getDurableObjectStub(runId, env)
    
    const config: RunConfig = {
      runId,
      modelProvider: body.modelProvider || 'openrouter',
      modelName: body.modelName,
      startLevel: body.startLevel || 0,
      endLevel: body.endLevel || 33,
      maxRetries: body.maxRetries || 3,
      streamingMode: body.streamingMode || 'selective',
      apiKey: body.apiKey,
    }
    
    const response = await stub.fetch(`http://do/start`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(config),
    })

    const data = await response.json()
    return NextResponse.json(data, { status: response.status })
  } catch (error) {
    console.error('Agent start error:', error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Unknown error' },
      { status: 500 }
    )
  }
}


