import request from '../utils/request'
import { reactive } from 'vue'
import { showFailToast } from 'vant'
import useLoading from './loading'

interface CozeMessage {
  role: 'user' | 'assistant'
  content: string
  reasoning_content?: string
  follow_up_questions?: string[]
  metadata?: any
}

interface CozeSession {
  session_id: string
  user_id: string
  bot_id: string
  status: string
  created_at: string
  updated_at: string
}

interface CozeChat {
  chat_id: string
  session_id: string
  message: string
  response: string
  status: string
  created_at: string
}

interface CozeStore {
  currentSession: CozeSession | null
  messages: CozeMessage[]
  isProcessing: boolean
}

const store = reactive<CozeStore>({
  currentSession: null,
  messages: [],
  isProcessing: false
})

/** 统一后端 success/data 与前端 r/d 的格式，保证认证与 Coze 接口都能正确解析 */
function normalizeCozeResponse(res: any): { r: boolean; d: any; e: string | null } {
  if (!res || typeof res !== 'object') return { r: false, d: res, e: res?.e ?? '无效响应' }
  const r = res.r === true || res.success === true
  const d = res.d ?? res.data
  const e = res.e ?? (typeof res.error === 'object' ? res.error?.message : res.error) ?? null
  return { r, d, e }
}

export default function useCoze() {
  const { load_start, load_done } = useLoading()

  /**
   * 创建新的 Coze 会话
   */
  async function createSession(userId: string, additionalMessages: any[] = [], autoSaveHistory: boolean = true, metaData: any = {}) {
    try {
      load_start()
      const raw = await request({
        url: '/coze/sessions',
        method: 'POST',
        data: {
          user_id: userId,
          additional_messages: additionalMessages,
          auto_save_history: autoSaveHistory,
          meta_data: metaData
        }
      })
      const { r, d, e } = normalizeCozeResponse(raw)

      if (r && d?.task_result) {
        const taskResult = d.task_result
        // 后端 create_session 返回 task_result = { data: session }；get_session 等可能直接返回 session 对象
        const sessionData = taskResult?.data ?? (taskResult?.session_id ? taskResult : null)
        if (!sessionData?.session_id) {
          console.error('创建会话响应缺少 session_id:', raw)
          showFailToast('会话数据格式异常')
          return null
        }
        store.currentSession = sessionData
        return sessionData
      } else {
        let msg = e || '创建会话失败'
        if (raw?.statusCode === 401 || (typeof e === 'string' && (e.includes('SudoerToken') || e.includes('HtyHost') || e.includes('Login')))) {
          msg = 'AI 客服需要登录态：请先打开首页（带 unionid 与 status=2）完成登录并选择测试身份，再回到本页发送消息'
        }
        showFailToast(msg)
        return null
      }
    } catch (error: any) {
      console.error('创建会话异常:', error, error?.response ?? error?.message)
      const detail = error?.e ?? error?.response?.data?.e ?? error?.response?.data?.error?.message ?? error?.message
      showFailToast(detail ? `创建会话失败：${detail}` : '创建会话失败（可能为网络或 CORS）')
      return null
    } finally {
      load_done()
    }
  }

  /**
   * 获取会话信息
   */
  async function getSession(sessionId: string) {
    try {
      const raw = await request({ url: `/coze/sessions/${sessionId}`, method: 'GET' })
      const { r, d, e } = normalizeCozeResponse(raw)
      if (r && d?.task_result) {
        store.currentSession = d.task_result
        return d.task_result
      } else {
        showFailToast(e || '获取会话失败')
        return null
      }
    } catch (error) {
      showFailToast('获取会话失败')
      return null
    }
  }

  /**
   * 发送消息
   * @param onStatusUpdate 轮询时的状态回调，与其它页面统一由上层展示状态
   */
  async function sendMessage(
    sessionId: string,
    message: string,
    stream: boolean = false,
    onStatusUpdate?: (status: string, details?: string) => void
  ) {
    if (!message.trim()) return null

    try {
      store.isProcessing = true
      store.messages.push({ role: 'user', content: message })

      const raw = await request({
        url: `/coze/sessions/${sessionId}/messages`,
        method: 'POST',
        data: { message, stream }
      })
      const { r, d, e } = normalizeCozeResponse(raw)
      if (r && d?.task_result) {
        const taskResult = d.task_result
        const chatId = taskResult.data?.chat_id || taskResult.chat_id
        if (chatId) {
          const chatResult = await waitForChatCompletion(chatId, 120000, 2000, onStatusUpdate)
          if (chatResult) {
            store.messages.push({
              role: 'assistant',
              content: chatResult.content || '',
              reasoning_content: chatResult.reasoning_content,
              follow_up_questions: chatResult.follow_up_questions,
              metadata: chatResult.metadata
            })
            return { ...taskResult, chat_result: chatResult }
          }
        }
        if (taskResult.response) {
          store.messages.push({
            role: 'assistant',
            content: taskResult.response
          })
        }
        return taskResult
      } else {
        showFailToast(e || '发送消息失败')
        return null
      }
    } catch (error) {
      showFailToast('发送消息失败')
      return null
    } finally {
      store.isProcessing = false
    }
  }

  /**
   * 等待聊天完成并获取结果
   * @param onStatusUpdate 轮询时回调状态，供页面展示（与其它页面统一由 request + 状态展示）
   */
  async function waitForChatCompletion(
    chatId: string,
    maxWaitTime: number = 120000,
    pollInterval: number = 2000,
    onStatusUpdate?: (status: string, details?: string) => void
  ) {
    const startTime = Date.now()
    let attemptCount = 0

    while (true) {
      const elapsedTime = Date.now() - startTime
      if (elapsedTime >= maxWaitTime) return null
      attemptCount++

      try {
        const raw = await request({
          url: `/coze/chats/${chatId}/result`,
          method: 'GET'
        })
        const { r, d } = normalizeCozeResponse(raw)
        if (r && d?.task_result) {
          const taskResult = d.task_result
          const currentStatus = d.task_status
          const elapsedSec = Math.floor(elapsedTime / 1000)
          onStatusUpdate?.(currentStatus, `${elapsedSec}s 第${attemptCount}次检查`)

          if (currentStatus === 'completed') {
            const data = taskResult.data || taskResult
            return {
              content: data.content || data.response || '',
              reasoning_content: data.reasoning_content,
              follow_up_questions: data.follow_up_questions,
              metadata: data.metadata,
              status: data.status
            }
          }
          if (currentStatus === 'failed') return null
        }
      } catch (_) {}
      
      // 等待后再次检查
      await new Promise(resolve => setTimeout(resolve, pollInterval))
    }
  }

  /**
   * 获取聊天结果（单次获取，不等待）
   */
  async function getChatResult(chatId: string) {
    try {
      const raw = await request({ url: `/coze/chats/${chatId}/result`, method: 'GET' })
      const { r, d, e } = normalizeCozeResponse(raw)
      if (r && d?.task_result) return d.task_result
      showFailToast(e || '获取聊天结果失败')
      return null
    } catch (error) {
      showFailToast('获取聊天结果失败')
      return null
    }
  }

  /**
   * 获取会话的所有聊天记录
   */
  async function getSessionChats(sessionId: string) {
    try {
      const raw = await request({ url: `/coze/sessions/${sessionId}/chats`, method: 'GET' })
      const { r, d, e } = normalizeCozeResponse(raw)
      if (r && d?.task_result) {
        // 将聊天记录转换为消息格式
        const messages: CozeMessage[] = []
        d.task_result.forEach((chat: CozeChat) => {
          messages.push(
            { role: 'user', content: chat.message },
            { role: 'assistant', content: chat.response }
          )
        })
        store.messages = messages
        return d.task_result
      } else {
        showFailToast(e || '获取聊天记录失败')
        return null
      }
    } catch (error) {
      showFailToast('获取聊天记录失败')
      return null
    }
  }

  /**
   * 获取用户的所有会话
   */
  async function getUserSessions(userId: string) {
    try {
      const raw = await request({ url: `/coze/users/${userId}/sessions`, method: 'GET' })
      const { r, d, e } = normalizeCozeResponse(raw)
      if (r && d?.task_result) {
        return d.task_result
      } else {
        showFailToast(e || '获取用户会话失败')
        return null
      }
    } catch (error) {
      showFailToast('获取用户会话失败')
      return null
    }
  }

  /**
   * 终止会话
   */
  async function terminateSession(sessionId: string) {
    try {
      const raw = await request({ url: `/coze/sessions/${sessionId}`, method: 'DELETE' })
      const { r, e } = normalizeCozeResponse(raw)
      if (r) {
        store.currentSession = null
        store.messages = []
        return true
      } else {
        showFailToast(e || '终止会话失败')
        return false
      }
    } catch (error) {
      showFailToast('终止会话失败')
      return false
    }
  }

  /**
   * 重置本地状态
   */
  function resetStore() {
    store.currentSession = null
    store.messages = []
    store.isProcessing = false
  }

  /**
   * 添加消息到本地状态
   */
  function addMessage(message: CozeMessage) {
    store.messages.push(message)
  }

  /**
   * 清空消息历史
   */
  function clearMessages() {
    store.messages = []
  }

  return {
    store,
    createSession,
    getSession,
    sendMessage,
    waitForChatCompletion,
    getChatResult,
    getSessionChats,
    getUserSessions,
    terminateSession,
    resetStore,
    addMessage,
    clearMessages
  }
}