import { NextRequest, NextResponse } from 'next/server'
import { signByteplusRequest } from '@/lib/http/byteplus-signature'

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { taskId, roomId, userId, aiId } = body

    const endpoint = 'https://open.byteplusapi.com?Action=StartVoiceChat&Version=2025-05-01'

    const payload = JSON.stringify({
      AppId: process.env.NEXT_PUBLIC_RTC_APP_ID,
      RoomId: roomId,
      TaskId: taskId,
      Config: {
        ASRConfig: {
          Provider: 'BytePlus',
          ProviderParams: {
            Mode: process.env.BYTEPLUS_ASR_MODE || 'SeedASR',
            Language: process.env.BYTEPLUS_ASR_LANG || 'zh-CN',
            AppId: process.env.BYTEPLUS_APP_ID,
            AccessToken: process.env.BYTEPLUS_ACCESS_TOKEN,
            StreamMode: Number(process.env.BYTEPLUS_ASR_STREAM_MODE || 0),
          },
          TurnDetectionMode: 1,
        },
        TTSConfig: {
          Provider: 'BytePlus',
          ProviderParams: {
            app: {
              appid: process.env.BYTEPLUS_APP_ID,
              token: process.env.BYTEPLUS_ACCESS_TOKEN,
            },
            audio: {
              voice_type: 'S_vrx7PzCx1',
              pitch_rate: 5,
              speech_rate: 5,
              // voice_type: 'zh_female_cancan_mars_bigtts'
            },
            // ResourceId: "volc.service_type.1000009",
            ResourceId: 'volc.megatts.default',
          },
        },
        LLMConfig: {
          Provider: 'BytePlus',
          EndPointId: process.env.BYTEPLUS_LLM_ENDPOINT_ID,
          APIKey: process.env.BYTEPLUS_LLM_API_KEY,
          SystemMessages: ['You are an assistant, with a humorous and understanding personality'],
          ThinkingType: 'disabled',
        },
      },
      AgentConfig: {
        TargetUserID: [`${userId}`],
        WelcomeMessage: '大家好，我是mzc-ai，0，2000年出生的理性高智智者，愿与你共享知识。',
        UserID: `${aiId}`,
        EnableConversationStateCallback: true,
      },
    })

    const { headers, url } = signByteplusRequest(
      {
        accessKeyId: process.env.BYTEPLUS_AK as string,
        secretAccessKey: process.env.BYTEPLUS_SK as string,
        region: process.env.BYTEPLUS_REGION || 'ap-singapore-1',
        service: process.env.BYTEPLUS_SERVICE || 'rtc',
      },
      {
        method: 'POST',
        url: endpoint,
        headers: {
          'content-type': 'application/json; charset=utf-8',
        },
        body: payload,
      }
    )

    const res = await fetch(url, {
      method: 'POST',
      headers,
      body: payload,
    })
    console.log('res', res)
    return NextResponse.json(await res.json())
  } catch (error) {
    return NextResponse.json({ error: '服务器错误' }, { status: 500 })
  }
}
