import type { Answer, ChatRecord, OriginalRecord } from '@/types/chat'

/**
 * 从 query_user_qa_record_list 返回列表的「最后一条」中提取 workflow 上下文。
 * 优先在最后一条记录的 answerList 中从后往前找到同时带有 recordType 与 workFlowSessionId 的答案。
 */
export function getLastQaRecordWorkflowContext(qaRecords: OriginalRecord[] | null | undefined): {
  recordType?: string
  workFlowSessionId?: string
  busiType?: string
} {
  if (!Array.isArray(qaRecords) || qaRecords.length === 0)
    return {}
  const lastRecord = qaRecords[qaRecords.length - 1]
  const list = lastRecord?.answerList
  if (!Array.isArray(list) || list.length === 0)
    return {}

  for (let i = list.length - 1; i >= 0; i--) {
    const a = list[i] as Answer
    const recordType = a?.recordType != null ? String(a.recordType).trim() : ''
    const workFlowSessionId = a?.workFlowSessionId != null ? String(a.workFlowSessionId).trim() : ''
    if (recordType && workFlowSessionId) {
      const busiType = a?.busiType != null ? String(a.busiType).trim() : ''
      return {
        recordType,
        workFlowSessionId,
        ...(busiType ? { busiType } : {}),
      }
    }
  }
  return {}
}

export function processApiResponse(data: OriginalRecord[]): ChatRecord[] {
  const chatRecord: ChatRecord[] = []
  if (data.length === 0)
    return chatRecord
  data.forEach((record) => {
    // 如果没有 question 字段（后端未返回问题文案），则不生成用户问题气泡，避免展示“空气炮”
    if (record.question) {
      chatRecord.push({
        role: 'user',
        ...record,
      })
    }

    if (record.answerList && record.answerList.length > 0) {
      record.answerList.forEach((answer) => {
        answer.isShow = true
      })
      chatRecord.push({
        role: 'ai',
        answerList: record.answerList,
        question: record.question,
        toolId: record.toolId,
      })
    }
  })

  return chatRecord
}
