/**
 * Specialist-Agent API Proxy
 * Proxies /api/sdk/v1/specialist-agent/* → backend-compliance:8002/api/v1/specialist-agent/*
 *
 * Streaming routes (SSE /test/stream/{run_id}) pass through unmodified.
 */

import { NextRequest, NextResponse } from 'next/server'

const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'

async function proxyRequest(
  request: NextRequest,
  pathSegments: string[] | undefined,
  method: string,
) {
  const pathStr = pathSegments?.join('/') || ''
  const searchParams = request.nextUrl.searchParams.toString()
  const basePath = `${BACKEND_URL}/api/compliance/specialist-agent`
  const url = pathStr
    ? `${basePath}/${pathStr}${searchParams ? `?${searchParams}` : ''}`
    : `${basePath}${searchParams ? `?${searchParams}` : ''}`

  const isSSE = pathStr.startsWith('test/stream/')

  try {
    const headers: HeadersInit = {}
    if (!isSSE) headers['Content-Type'] = 'application/json'

    const fetchOptions: RequestInit = {
      method,
      headers,
      signal: AbortSignal.timeout(isSSE ? 600000 : 60000),
    }
    if (method === 'POST' || method === 'PUT' || method === 'PATCH' ||
        method === 'DELETE') {
      const body = await request.text()
      if (body) fetchOptions.body = body
    }

    const response = await fetch(url, fetchOptions)

    if (isSSE) {
      return new NextResponse(response.body, {
        status: response.status,
        headers: {
          'Content-Type': 'text/event-stream',
          'Cache-Control': 'no-cache',
          'Connection': 'keep-alive',
          'X-Accel-Buffering': 'no',
        },
      })
    }

    if (!response.ok) {
      const errText = await response.text()
      let errJson
      try { errJson = JSON.parse(errText) }
      catch { errJson = { error: errText } }
      return NextResponse.json(
        { error: `Backend Error: ${response.status}`, ...errJson },
        { status: response.status },
      )
    }

    const ct = response.headers.get('content-type') || ''
    if (ct.includes('application/json')) {
      const data = await response.json()
      return NextResponse.json(data)
    }
    // Binary asset (image/video/csv etc.)
    const blob = await response.blob()
    return new NextResponse(blob, {
      status: response.status,
      headers: {
        'Content-Type': ct || 'application/octet-stream',
        'Content-Disposition':
          response.headers.get('content-disposition') || '',
      },
    })
  } catch (e) {
    console.error('specialist-agent proxy error:', e)
    return NextResponse.json(
      { error: 'Verbindung zum Backend fehlgeschlagen' },
      { status: 503 },
    )
  }
}

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ path?: string[] }> },
) {
  const { path } = await params
  return proxyRequest(request, path, 'GET')
}

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ path?: string[] }> },
) {
  const { path } = await params
  return proxyRequest(request, path, 'POST')
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ path?: string[] }> },
) {
  const { path } = await params
  return proxyRequest(request, path, 'DELETE')
}
