export const dynamic = 'force-dynamic'
export const runtime = 'nodejs'

import { NextResponse } from 'next/server'
import { voiceBus, VoiceEventPayload } from '@/lib/voice-bus'

const ALLOWED_EVENTS = new Set(['wake', 'command', 'response', 'idle', 'error'])

export async function POST(req: Request) {
  const expected = process.env.VOICE_API_KEY
  if (!expected) {
    return NextResponse.json({ error: 'voice_not_configured' }, { status: 503 })
  }

  const auth = req.headers.get('authorization') || ''
  const token = auth.replace(/^Bearer\s+/i, '').trim()
  if (token !== expected) {
    return NextResponse.json({ error: 'unauthorized' }, { status: 401 })
  }

  const body = await req.json().catch(() => null)
  if (!body || typeof body.event !== 'string' || !ALLOWED_EVENTS.has(body.event)) {
    return NextResponse.json({ error: 'invalid_event' }, { status: 400 })
  }

  const agent = body.agent === 'lusya' ? 'lusya' : body.agent === 'cosmo' ? 'cosmo' : undefined

  const evt: VoiceEventPayload = {
    event: body.event,
    agent,
    text: typeof body.text === 'string' ? body.text.slice(0, 2000) : undefined,
    timestamp: new Date().toISOString(),
  }

  voiceBus.emit('voice', evt)
  return NextResponse.json({ ok: true })
}
