/**
 * Coze Realtime 语音面试 Hook
 * 
 * 基于 Coze 官方 SDK (@coze/realtime-api) 实现语音面试
 * 
 * 架构说明：
 * 1. 使用 @coze/realtime-api SDK 直接连接
 * 2. 在 bot.join 后通过 sendMessage 发送 session.update 信令传递 session_id
 * 
 * 参考文档：
 * - https://www.coze.cn/open/docs/dev_how_to_guides/Realtime_web
 * - https://www.coze.cn/open/docs/developer_guides/signaling_uplink_event
 * - https://github.com/coze-dev/coze-js/blob/main/examples/realtime-quickstart-react/src/App.tsx
 */
import { ref, computed } from 'vue'
import type { RTCConnectionState } from '@/types'

// Coze Realtime 连接参数
interface CozeRealtimeParams {
  accessToken: string   // PAT Token
  botId: string         // 智能体 ID
  sessionId: string     // 面试会话 ID（关键：需要传递给工作流）
  voiceId?: string      // 音色 ID（可选）
}

// 音频配置（根据 Coze 官方文档 session.update 事件参数）
const AUDIO_CONFIG = {
  // VAD（语音活动检测）配置
  // 注意：silence_duration_ms 取值范围 200~2000，默认 500
  vad: {
    silenceDurationMs: 800,         // 静音持续 0.8 秒判定为说话结束（降低延迟）
    prefixPaddingMs: 300,           // 前置填充 300ms（防止开头被截断）
  },
  // 打断配置
  allowVoiceInterrupt: false,       // 禁止语音打断 AI
}

// 本地 VAD 配置
const LOCAL_VAD_CONFIG = {
  enabled: true,                    // 启用本地 VAD
  volumeThreshold: 0.15,            // 音量阈值（0-1），15% 过滤环境噪音和回声
  silenceTimeout: 800,              // 静音超时（毫秒），持续静音后触发 commit
  minSpeechDuration: 300,           // 最小说话时长（毫秒），防止误触发
  checkInterval: 50,                // 检测间隔（毫秒）
}

// 信令事件名称（来自 @coze/realtime-api EventNames）
// 注意：实际使用时从 SDK 动态导入，这里仅作为类型参考
const _EventNamesRef = {
  ALL: 'realtime.event',
  ALL_CLIENT: 'client.*',
  ALL_SERVER: 'server.*',
  CONNECTED: 'client.connected',
  INTERRUPTED: 'client.interrupted',
  DISCONNECTED: 'client.disconnected',
  AUDIO_UNMUTED: 'client.audio.unmuted',
  AUDIO_MUTED: 'client.audio.muted',
  ERROR: 'client.error',
}
void _EventNamesRef // 避免 unused 警告

/**
 * Coze Realtime Hook
 * 使用 Coze 官方 SDK 进行语音面试
 */
export function useCozeRealtime() {
  const connectionState = ref<RTCConnectionState>('disconnected')
  const isMuted = ref(false)
  const sessionId = ref('')
  const isSessionUpdateSent = ref(false)
  const lastError = ref<string | null>(null)

  // 通讯时间线（用于调试显示）
  interface TimelineEvent {
    time: string      // HH:MM:SS.mmm 格式
    type: 'send' | 'receive' | 'audio' | 'system' | 'error'
    event: string     // 事件名
    detail?: string   // 详情
  }
  const timeline = ref<TimelineEvent[]>([])
  
  // 添加时间线事件
  function addTimelineEvent(type: TimelineEvent['type'], event: string, detail?: string) {
    const now = new Date()
    const time = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}.${String(now.getMilliseconds()).padStart(3, '0')}`
    timeline.value.push({ time, type, event, detail })
    // 保留最近 50 条
    if (timeline.value.length > 50) {
      timeline.value.shift()
    }
  }

  // 调试信息
  const debugInfo = ref<{
    rtcConnected: boolean
    sessionUpdateSent: boolean
    sessionId: string
    botJoined: boolean
    eventsSent: string[]
    eventsReceived: string[]
    errors: string[]
  }>({
    rtcConnected: false,
    sessionUpdateSent: false,
    sessionId: '',
    botJoined: false,
    eventsSent: [],
    eventsReceived: [],
    errors: [],
  })

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  let client: any = null

  // ============ 本地 VAD 相关 ============
  const isSpeaking = ref(false)           // 用户是否正在说话
  const isAISpeaking = ref(false)         // AI 是否正在说话（用于暂停收音）
  const currentVolume = ref(0)            // 当前音量（0-1）
  let audioContext: AudioContext | null = null
  let analyser: AnalyserNode | null = null
  let mediaStream: MediaStream | null = null
  let vadCheckInterval: number | null = null
  let silenceStartTime: number | null = null
  let speechStartTime: number | null = null
  let hasCommittedThisTurn = false        // 本轮是否已提交

  /**
   * 启动本地 VAD 监测
   */
  async function startLocalVAD() {
    if (!LOCAL_VAD_CONFIG.enabled) return
    
    try {
      // 获取麦克风音频流（开启回声消除和噪音抑制）
      mediaStream = await navigator.mediaDevices.getUserMedia({ 
        audio: {
          echoCancellation: true,      // 回声消除（消除扬声器声音）
          noiseSuppression: true,      // 噪音抑制
          autoGainControl: true,       // 自动增益控制
        }
      })
      audioContext = new (window.AudioContext || (window as any).webkitAudioContext)()
      analyser = audioContext.createAnalyser()
      analyser.fftSize = 512
      analyser.smoothingTimeConstant = 0.4  // 提高平滑度，减少抖动
      
      const source = audioContext.createMediaStreamSource(mediaStream)
      source.connect(analyser)
      
      const dataArray = new Uint8Array(analyser.frequencyBinCount)
      
      // 定期检测音量
      vadCheckInterval = window.setInterval(() => {
        if (!analyser || isMuted.value) return
        
        analyser.getByteFrequencyData(dataArray)
        
        // 计算平均音量（归一化到 0-1）
        const sum = dataArray.reduce((a, b) => a + b, 0)
        const avg = sum / dataArray.length / 255
        currentVolume.value = avg
        
        // 注意：不再基于 isAISpeaking 暂停收音
        // 依赖浏览器的回声消除 + 较高的音量阈值来过滤 AI 声音
        
        const now = Date.now()
        
        if (avg > LOCAL_VAD_CONFIG.volumeThreshold) {
          // 检测到声音
          if (!isSpeaking.value) {
            isSpeaking.value = true
            speechStartTime = now
            silenceStartTime = null
            hasCommittedThisTurn = false
            addTimelineEvent('audio', '🎤 检测到说话', `音量: ${(avg * 100).toFixed(1)}%`)
            console.log(`🎤 [LocalVAD] 检测到说话, 音量: ${(avg * 100).toFixed(1)}%`)
          }
          silenceStartTime = null
        } else if (isSpeaking.value) {
          // 正在说话但当前静音
          if (!silenceStartTime) {
            silenceStartTime = now
          }
          
          const silenceDuration = now - silenceStartTime
          const speechDuration = speechStartTime ? now - speechStartTime : 0
          
          // 检查是否满足提交条件
          if (silenceDuration >= LOCAL_VAD_CONFIG.silenceTimeout && 
              speechDuration >= LOCAL_VAD_CONFIG.minSpeechDuration &&
              !hasCommittedThisTurn) {
            // 静音超时，触发提交
            isSpeaking.value = false
            hasCommittedThisTurn = true
            addTimelineEvent('audio', '🔇 说话结束', `静音 ${silenceDuration}ms`)
            console.log(`🔇 [LocalVAD] 说话结束, 静音 ${silenceDuration}ms, 自动提交`)
            
            // 自动发送 commit
            commitAudioInputInternal()
          }
        }
      }, LOCAL_VAD_CONFIG.checkInterval)
      
      addTimelineEvent('system', '🎙️ 本地VAD启动', `阈值: ${LOCAL_VAD_CONFIG.volumeThreshold}, 静音: ${LOCAL_VAD_CONFIG.silenceTimeout}ms`)
      console.log('✅ [LocalVAD] 本地 VAD 已启动')
    } catch (error) {
      console.error('❌ [LocalVAD] 启动失败:', error)
      addTimelineEvent('error', '❌ VAD启动失败', String(error))
    }
  }

  /**
   * 停止本地 VAD 监测
   */
  function stopLocalVAD() {
    if (vadCheckInterval) {
      clearInterval(vadCheckInterval)
      vadCheckInterval = null
    }
    if (mediaStream) {
      mediaStream.getTracks().forEach(track => track.stop())
      mediaStream = null
    }
    if (audioContext) {
      audioContext.close()
      audioContext = null
    }
    analyser = null
    isSpeaking.value = false
    currentVolume.value = 0
    console.log('🛑 [LocalVAD] 已停止')
  }

  /**
   * 内部提交函数（供 VAD 调用）
   */
  function commitAudioInputInternal() {
    if (!client) return false
    
    const commitEvent = {
      id: `evt_${Date.now()}_commit`,
      event_type: 'input_audio_buffer.commit',
    }
    
    try {
      client.sendMessage(commitEvent)
      addTimelineEvent('send', '📤 语音已提交', '本地VAD触发')
      console.log('📤 [LocalVAD] 已发送 commit')
      debugInfo.value.eventsSent.push('input_audio_buffer.commit (local_vad)')
      return true
    } catch (error) {
      console.error('❌ [LocalVAD] commit 失败:', error)
      return false
    }
  }

  /**
   * 连接到 Coze 语音房间
   * 
   * 使用 @coze/realtime-api SDK 连接
   */
  async function connect(params: CozeRealtimeParams) {
    try {
      connectionState.value = 'connecting'
      lastError.value = null
      sessionId.value = params.sessionId
      
      // 更新调试信息
      debugInfo.value.sessionId = params.sessionId
      debugInfo.value.eventsSent = []
      debugInfo.value.eventsReceived = []
      debugInfo.value.errors = []
      
      // 清空时间线
      timeline.value = []
      addTimelineEvent('system', '🚀 开始连接', `session: ${params.sessionId.slice(-8)}`)

      console.log('=== Coze Realtime: Starting connection ===')
      console.log('Session ID:', params.sessionId)
      console.log('Bot ID:', params.botId)

      // 1. 动态导入 Coze Realtime SDK
      console.log('Step 1: Loading @coze/realtime-api SDK...')
      const { RealtimeClient, RealtimeUtils, EventNames: SDKEventNames } = await import('@coze/realtime-api')

      // 2. 检查设备权限
      console.log('Step 2: Checking device permission...')
      const permission = await RealtimeUtils.checkDevicePermission()
      if (!permission.audio) {
        throw new Error('需要麦克风访问权限。请在浏览器地址栏左侧的锁图标中授权。')
      }
      console.log('✅ Microphone permission granted')

      // 3. 恢复音频上下文（解决浏览器自动播放限制）
      console.log('Step 3: Resuming AudioContext for autoplay...')
      try {
        // 创建并恢复音频上下文，确保音频可以播放
        const audioContext = new (window.AudioContext || (window as any).webkitAudioContext)()
        if (audioContext.state === 'suspended') {
          await audioContext.resume()
          console.log('✅ AudioContext resumed')
        }
      } catch (audioErr) {
        console.warn('AudioContext resume failed:', audioErr)
      }

      // 4. 初始化客户端（含音频配置）
      console.log('Step 4: Initializing RealtimeClient...')
      console.log('Audio config:', AUDIO_CONFIG)
      client = new RealtimeClient({
        accessToken: params.accessToken,
        botId: params.botId,
        connectorId: '1024',  // 固定值
        voiceId: params.voiceId,
        allowPersonalAccessTokenInBrowser: true,
        debug: true,
        // 🔊 音频配置
        audioMutedDefault: false,  // 默认不静音，启用音频播放
        suppressStationaryNoise: true, // 抑制静态噪音
      })

      // 5. 配置事件监听
      console.log('Step 5: Setting up event listeners...')
      setupEventListeners(SDKEventNames, params.sessionId)

      // 6. 建立连接
      console.log('Step 6: Connecting to Coze...')
      await client.connect()
      
      // 7. 确保音频输出启用
      console.log('Step 7: Ensuring audio output is enabled...')
      try {
        // 尝试播放一个静音音频来解锁音频播放
        const silentAudio = new Audio('data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA')
        silentAudio.volume = 0.01
        await silentAudio.play().catch(() => {})
        console.log('✅ Audio output unlocked')
      } catch (e) {
        console.warn('Audio unlock attempt:', e)
      }

      debugInfo.value.rtcConnected = true
      connectionState.value = 'connected'
      console.log('=== Coze Realtime: Connected successfully ===')

      // 8. 确保远程音频播放已启用
      console.log('Step 8: Enabling remote audio playback...')
      try {
        // 尝试启用远程音频播放（AI 的声音）
        if (typeof client.setRemoteAudioEnable === 'function') {
          await client.setRemoteAudioEnable(true)
          console.log('✅ Remote audio playback enabled via setRemoteAudioEnable')
        }
        // 尝试通过 RTC 引擎设置
        const rtcEngine = client.getRtcEngine?.()
        if (rtcEngine) {
          console.log('📻 RTC Engine available, checking audio settings...')
          if (typeof rtcEngine.setRemoteAudioPlaybackVolume === 'function') {
            rtcEngine.setRemoteAudioPlaybackVolume('*', 100)
            console.log('✅ Remote audio volume set to 100')
          }
          if (typeof rtcEngine.subscribeAllRemoteAudio === 'function') {
            rtcEngine.subscribeAllRemoteAudio()
            console.log('✅ Subscribed to all remote audio')
          }
        }
      } catch (e) {
        console.warn('Remote audio setup:', e)
      }

      // 9. 启动本地 VAD（更快响应）
      console.log('Step 9: Starting local VAD...')
      await startLocalVAD()

    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : String(error)
      console.error('Coze Realtime connect error:', error)
      lastError.value = errorMessage
      debugInfo.value.errors.push(errorMessage)
      connectionState.value = 'failed'
      throw error
    }
  }

  /**
   * 设置事件监听器
   */
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  function setupEventListeners(SDKEventNames: any, sid: string) {
    if (!client) return

    console.log('🎧 Setting up event listeners...')
    console.log('Available EventNames:', Object.keys(SDKEventNames))
    
    addTimelineEvent('system', '🔌 连接建立', '开始监听事件')

    // 监听所有服务端事件
    client.on(SDKEventNames.ALL_SERVER, (eventName: string, event: unknown) => {
      const timestamp = new Date().toLocaleTimeString()
      console.log(`📩 [${timestamp}] Server event: ${eventName}`, event)
      debugInfo.value.eventsReceived.push(`${eventName} @ ${timestamp}`)

      // 当 Bot 加入房间后，发送 session.update 事件
      if (eventName === 'server.bot.join') {
        console.log('🤖 Bot joined! Sending session.update...')
        debugInfo.value.botJoined = true
        addTimelineEvent('receive', '🤖 Bot 加入', 'server.bot.join')
        sendSessionUpdate(sid)
      }

      // 用户开始说话
      if (eventName === 'server.input_audio_buffer.speech_started') {
        addTimelineEvent('audio', '🎤 检测到说话', '用户开始说话')
      }
      
      // 用户停止说话（VAD 触发）
      if (eventName === 'server.input_audio_buffer.speech_stopped') {
        addTimelineEvent('audio', '🔇 说话结束', 'VAD 检测到静音')
      }
      
      // 语音提交到服务器
      if (eventName === 'server.input_audio_buffer.committed') {
        addTimelineEvent('send', '📤 语音已提交', '等待 AI 处理')
      }
      
      // AI 开始处理/思考
      if (eventName === 'server.conversation.item.created') {
        addTimelineEvent('receive', '🧠 AI 开始处理', 'conversation.item.created')
      }

      // AI 开始回复（流式）
      if (eventName === 'server.conversation.message.delta') {
        // 只记录第一次 delta（避免太多条目）
        const lastEvent = timeline.value[timeline.value.length - 1]
        if (!lastEvent || lastEvent.event !== '💬 AI 回复中') {
          isAISpeaking.value = true  // 🔇 AI 开始说话，暂停用户收音
          addTimelineEvent('receive', '💬 AI 回复中', '开始接收语音流（暂停收音）')
        }
      }
      
      // AI 回复完成
      if (eventName === 'server.conversation.message.completed') {
        addTimelineEvent('receive', '✅ AI 回复完成', 'message.completed')
        // 延迟后重置 AI 说话状态（用于 UI 显示）
        setTimeout(() => {
          if (isAISpeaking.value) {
            isAISpeaking.value = false
          }
        }, 1000)
      }
      
      // AI 开始说话（用于 UI 显示，不影响收音）
      if (eventName === 'server.audio.agent.speech_started') {
        isAISpeaking.value = true
        addTimelineEvent('receive', '🔊 AI 开始说话', eventName)
      }
      
      // AI 说话结束（用于 UI 显示）
      if (eventName === 'server.audio.agent.speech_stopped') {
        isAISpeaking.value = false
        addTimelineEvent('receive', '🔈 AI 说话结束', eventName)
      }
      
      // 回合结束
      if (eventName === 'server.response.done') {
        isAISpeaking.value = false
        addTimelineEvent('receive', '🏁 回合结束', 'response.done')
      }
      
      // 记录所有包含 audio 的事件（用于调试）
      if (eventName.toLowerCase().includes('audio')) {
        console.log(`🔊 [Audio Event] ${eventName}:`, event)
      }
    })

    // 监听客户端事件
    client.on(SDKEventNames.CONNECTED, () => {
      console.log('✅ [Client] Connected to Coze Realtime')
      debugInfo.value.eventsReceived.push('client.connected')
      addTimelineEvent('system', '✅ 已连接', 'RTC 连接成功')
    })

    client.on(SDKEventNames.DISCONNECTED, () => {
      console.log('❌ [Client] Disconnected from Coze Realtime')
      connectionState.value = 'disconnected'
      debugInfo.value.eventsReceived.push('client.disconnected')
      addTimelineEvent('system', '❌ 已断开', '连接断开')
    })

    client.on(SDKEventNames.INTERRUPTED, () => {
      console.log('⚠️ [Client] Interrupted')
      debugInfo.value.eventsReceived.push('client.interrupted')
      addTimelineEvent('system', '⚠️ 被打断', 'AI 被用户打断')
    })

    client.on(SDKEventNames.AUDIO_MUTED, () => {
      console.log('🔇 [Client] Audio muted')
      addTimelineEvent('audio', '🔇 麦克风关闭', '')
    })

    client.on(SDKEventNames.AUDIO_UNMUTED, () => {
      console.log('🔊 [Client] Audio unmuted')
      addTimelineEvent('audio', '🔊 麦克风开启', '')
    })

    client.on(SDKEventNames.ERROR, (error: unknown) => {
      const errorMessage = error instanceof Error ? error.message : String(error)
      console.error('❌ [Client] Error:', error)
      debugInfo.value.errors.push(errorMessage)
      addTimelineEvent('error', '❌ 错误', errorMessage)
    })

    // 监听所有事件（调试用）
    client.on(SDKEventNames.ALL, (eventName: string, data: unknown) => {
      // 避免重复日志，只记录非 server/client 前缀的事件
      if (!eventName.startsWith('server.') && !eventName.startsWith('client.')) {
        console.log(`📬 [ALL] Event: ${eventName}`, data)
      }
    })

    console.log('✅ Event listeners set up complete')
  }

  /**
   * 发送 session.update 信令事件
   * 
   * 根据 Coze 官方文档 signaling_uplink_event：
   * - 在 bot.join 后发送
   * - data.chat_config.parameters: 传递对话流自定义参数（如 session_id）
   * - data.chat_config.allow_voice_interrupt: 是否允许语音打断
   * - data.turn_detection: VAD 配置
   * 
   * 注意：只发送一次，避免 Bot 重连时重复发送导致对话重置
   */
  function sendSessionUpdate(sid: string) {
    if (!client || !sid) {
      console.warn('Cannot send session.update: client or sessionId is missing')
      return false
    }

    // 防止重复发送（Bot 重连时会再次触发 bot.join 事件）
    if (isSessionUpdateSent.value) {
      console.log('⚠️ session.update already sent, skipping to prevent conversation reset')
      return true
    }

    // 构造 session.update 事件（严格按照 Coze 文档格式）
    const event = {
      id: `evt_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      event_type: 'session.update',
      data: {
        // 会话配置
        chat_config: {
          // 传递对话流自定义参数
          parameters: {
            session_id: sid,
          },
          // 禁止语音打断 AI
          allow_voice_interrupt: AUDIO_CONFIG.allowVoiceInterrupt,
        },
        // VAD 声音检测配置
        turn_detection: {
          type: 'server_vad',                                    // 服务端 VAD
          silence_duration_ms: AUDIO_CONFIG.vad.silenceDurationMs, // 静音 2 秒判定说完（范围 200~2000）
          prefix_padding_ms: AUDIO_CONFIG.vad.prefixPaddingMs,     // 前置填充 600ms
        },
      },
    }

    console.log('📤 Sending session.update:', JSON.stringify(event, null, 2))

    try {
      // 使用 sendMessage 发送上行信令
      client.sendMessage(event)
      console.log('✅ session.update sent successfully!')
      console.log(`📊 VAD: silence=${AUDIO_CONFIG.vad.silenceDurationMs}ms, prefix=${AUDIO_CONFIG.vad.prefixPaddingMs}ms`)
      console.log(`🔇 Voice interrupt: ${AUDIO_CONFIG.allowVoiceInterrupt ? 'enabled' : 'disabled'}`)
      debugInfo.value.eventsSent.push('session.update')
      isSessionUpdateSent.value = true
      debugInfo.value.sessionUpdateSent = true
      return true
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : String(error)
      console.error('❌ Failed to send session.update:', error)
      debugInfo.value.errors.push(`sendMessage failed: ${errorMessage}`)
      return false
    }
  }

  /**
   * 断开连接
   */
  async function disconnect() {
    console.log('🔌 Disconnecting from Coze Realtime...')
    try {
      // 先停止本地 VAD
      stopLocalVAD()
      
      if (client) {
        // 先清除事件监听器
        try {
          client.clearEventHandlers?.()
        } catch (e) {
          console.warn('clearEventHandlers failed:', e)
        }
        
        // 断开连接（可能是异步的）
        try {
          await client.disconnect()
        } catch (e) {
          console.warn('disconnect call failed:', e)
        }
        
        client = null
      }
      
      connectionState.value = 'disconnected'
      isSessionUpdateSent.value = false
      debugInfo.value.rtcConnected = false
      debugInfo.value.sessionUpdateSent = false
      debugInfo.value.botJoined = false
      console.log('✅ Coze Realtime disconnected successfully')
    } catch (error) {
      console.error('❌ Disconnect error:', error)
      // 即使出错也要重置状态
      stopLocalVAD()
      connectionState.value = 'disconnected'
      client = null
    }
  }

  /**
   * 切换静音
   */
  async function toggleMute(mute: boolean) {
    if (client) {
      try {
        await client.setAudioEnable(!mute)
        isMuted.value = mute
      } catch (error) {
        console.error('Toggle mute error:', error)
      }
    }
  }

  /**
   * 打断 AI
   */
  function interrupt() {
    if (client) {
      try {
        client.interrupt()
      } catch (error) {
        console.error('Interrupt error:', error)
      }
    }
  }

  /**
   * 提交当前语音输入（手动触发 VAD 结束）
   * 发送 input_audio_buffer.commit 信令告诉服务器用户已说完
   */
  function commitAudioInput() {
    if (!client) {
      console.warn('Cannot commit audio: client is not connected')
      return false
    }

    // 🛑 立刻停止录音状态（用户点击了"说完了"）
    isSpeaking.value = false
    silenceStartTime = null
    speechStartTime = null
    hasCommittedThisTurn = true
    addTimelineEvent('send', '🛑 手动停止录音', '用户点击说完了')

    // 方案 1: 发送 input_audio_buffer.commit 事件（OpenAI 兼容格式）
    const commitEvent = {
      id: `evt_${Date.now()}_commit`,
      event_type: 'input_audio_buffer.commit',
    }

    console.log('📤 Sending input_audio_buffer.commit (手动触发 VAD 结束)...')

    try {
      client.sendMessage(commitEvent)
      console.log('✅ Audio input committed!')
      addTimelineEvent('send', '📤 语音已提交', '手动触发')
      debugInfo.value.eventsSent.push('input_audio_buffer.commit')
      return true
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : String(error)
      console.error('❌ Failed to commit audio:', error)
      
      // 方案 2: 如果 commit 不支持，尝试发送 conversation.item.create
      console.log('📤 Trying alternative: conversation.item.create...')
      try {
        const createEvent = {
          id: `evt_${Date.now()}_create`,
          event_type: 'conversation.item.create',
          data: {
            item: {
              type: 'message',
              role: 'user',
              content: [{ type: 'input_audio', audio: '' }]
            }
          }
        }
        client.sendMessage(createEvent)
        console.log('✅ Alternative event sent!')
        return true
      } catch (altError) {
        console.error('❌ Alternative also failed:', altError)
        debugInfo.value.errors.push(`commitAudio failed: ${errorMessage}`)
        return false
      }
    }
  }

  /**
   * 获取调试信息摘要
   */
  const debugSummary = computed(() => {
    return {
      ...debugInfo.value,
      connectionState: connectionState.value,
      isMuted: isMuted.value,
    }
  })

  return {
    connectionState,
    isMuted,
    sessionId,
    isSessionUpdateSent,
    lastError,
    debugInfo,
    debugSummary,
    timeline,  // 通讯时间线
    // 本地 VAD 状态
    isSpeaking,
    isAISpeaking,  // AI 是否正在说话
    currentVolume,
    connect,
    disconnect,
    toggleMute,
    interrupt,
    commitAudioInput,  // 手动触发 VAD 结束（说完了）
  }
}
