import { getRecord, updateRecord } from '../api'
import { useChat } from '@ezijing/ai-vue'
import { systemPrompt, getUserPrompt } from './prompt'

export function useLiveRecord({ id = '', immediate = false }: { id?: string; immediate?: boolean } = {}) {
  const { isLoading, generateText } = useChat({ provider: 'volcano' })
  const recordId = ref(id)
  const liveRecord = ref<any>(null)
  const statusText = ref('')
  const isPolling = ref(false)
  let pollingTimer: ReturnType<typeof setTimeout> | null = null

  const fetchLiveRecord = async () => {
    if (!recordId.value) return
    const res = await getRecord({ id: recordId.value })
    const resDetail = res.data.detail
    liveRecord.value = { ...resDetail, live_info: JSON.parse(resDetail.live_info) }
    return liveRecord.value
  }
  onMounted(() => {
    if (immediate && recordId.value) {
      fetchLiveRecord().then(() => {
        if (!liveRecord.value?.ai_analyze) handleAIScore()
      })
    }
  })

  const handleAIScore = async () => {
    const messages = [
      { role: 'system', content: systemPrompt },
      { role: 'user', content: getUserPrompt(liveRecord.value) },
    ]
    const result = await generateText({ messages, response_format: { type: 'json_object' } } as any)
    if (!result) return
    const aiAnalyze = result.content
      .replaceAll('卖点讲解覆盖情况', '')
      .replaceAll('违禁词分析报告', '')
      .replaceAll('直播优化建议', '')
      .replaceAll('语速分析报告', '')
    await updateRecord({ id: recordId.value, ai_analyze: aiAnalyze })
    if (immediate) fetchLiveRecord()
  }

  const startPolling = (id = '', interval = 3000) => {
    if (isPolling.value) return
    if (id) recordId.value = id

    isPolling.value = true

    const poll = async () => {
      if (!isPolling.value) return

      statusText.value = '口播内容识别中，请稍后...'
      const record = await fetchLiveRecord()

      if (record?.subtitle) {
        statusText.value = 'AI分析中，大约需要1分钟，请耐心等待...'
        await handleAIScore()
        stopPolling()
      } else {
        pollingTimer = setTimeout(poll, interval)
      }
    }

    poll()
  }

  const stopPolling = () => {
    isPolling.value = false
    statusText.value = ''
    if (pollingTimer) {
      clearTimeout(pollingTimer)
      pollingTimer = null
    }
  }

  onUnmounted(() => {
    stopPolling()
  })

  return { liveRecord, fetchLiveRecord, handleAIScore, startPolling, stopPolling, isPolling, isLoading, statusText }
}
