import axios from 'axios'
import md5 from 'blueimp-md5'
import { AIData, AIMessage } from './types'
import { extractJSON } from '@/utils/helper'
import { sseRequest, SSEOptions } from '@/utils/sseRequest'

function transform(messages: any[]): AIMessage {
  return messages.reduce(
    (result, message) => {
      let delta = null
      if (message.choices && message.choices.length > 0) {
        delta = message.choices[0].delta
      }
      const content = result.content + (delta.content || '')
      const reasoning_content = result.reasoning_content + (delta.reasoning_content || '')
      let full_content = ''
      if (reasoning_content) {
        full_content = `<div class="ai-thinking">${reasoning_content}`
        if (content) {
          full_content += `</div>${content}`
        }
      } else {
        full_content = content
      }
      return {
        id: message.id,
        role: 'assistant',
        content,
        reasoning_content,
        full_content,
        json: extractJSON(content),
      }
    },
    { content: '', reasoning_content: '' }
  )
}

// 文心一言
export async function yiyan(data: AIData, options: SSEOptions) {
  const AK = 'wY7bvMpkWeZbDVq9w3EDvpjU'
  const SK = 'XJwpiJWxs5HXkOtbo6tQrvYPZFJAWdAy'
  const resp = await axios.post(
    `/api/qianfan/oauth/2.0/token?grant_type=client_credentials&client_id=${AK}&client_secret=${SK}`
  )
  await sseRequest(
    `/api/qianfan/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token=${resp.data.access_token}`,
    {
      ...options,
      body: JSON.stringify({ stream: true, ...data }),
    },
    transform
  )
}

// DeepSeek
export async function deepseek(data: AIData, options: SSEOptions) {
  await sseRequest(
    '/api/deepseek/chat/completions',
    {
      ...options,
      headers: { 'Content-Type': 'application/json', Authorization: 'Bearer sk-f1a6f0a7013241de8393cb2cb108e777' },
      body: JSON.stringify({ model: 'deepseek-reasoner', stream: true, ...data }),
    },
    transform
  )
}

// SiliconFlow
export async function siliconflow(data: AIData, options: SSEOptions) {
  await sseRequest(
    '/api/siliconflow/v1/chat/completions',
    {
      ...options,
      headers: {
        'Content-Type': 'application/json',
        Authorization: 'Bearer sk-bivnwauskdbvpspvmdorrgkrpwlyfxbfcezqsfsevowzubdj',
      },
      body: JSON.stringify({ model: 'deepseek-ai/DeepSeek-R1', stream: true, ...data }),
    },
    transform
  )
}

// 通义千问
export async function qwen(data: AIData, options: SSEOptions) {
  await sseRequest(
    '/api/qwen/compatible-mode/v1/chat/completions',
    {
      ...options,
      headers: { 'Content-Type': 'application/json', Authorization: 'Bearer sk-afd0fcdb53bf4058b2068b8548820150' },
      body: JSON.stringify({ model: 'qwen-max-latest', stream: true, ...data }),
    },
    transform
  )
}

// 天工
export async function tiangong(data: AIData, options: SSEOptions) {
  const appKey = 'a8701b73637562d33a53c668a90ee3be'
  const appSecret = 'e191593f486bb88a39c634f46926762dddc97b9082e192af'
  const timestamp = Math.floor(Date.now() / 1000).toString()
  const sign = md5(`${appKey}${appSecret}${timestamp}`)

  await sseRequest('/api/tiangong/sky-saas-writing/api/v1/chat', {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      app_key: appKey,
      sign,
      timestamp,
      stream: 'true',
    },
    body: JSON.stringify({ chat_history: data.messages, stream_resp_type: 'delta' }),
  })
}

// OpenAI
export async function openAI(data: AIData, options: SSEOptions) {
  await sseRequest(
    '/api/openai/chat/create',
    {
      ...options,
      headers: { 'Content-Type': 'application/json', Authorization: 'ezijing@20250331' },
      body: JSON.stringify({ stream: true, ...data }),
    },
    transform
  )
}

const aiService = {
  async post(data: AIData, options: SSEOptions) {
    const messages: AIMessage[] = []
    const dataset = localStorage.getItem('dataset')
    if (dataset) {
      const datasetInfo = JSON.parse(dataset)
      messages.push({ role: 'system', content: `这是一个数据集：${JSON.stringify(datasetInfo)}` })
    }
    data.messages = [...messages, ...data.messages]

    const providers = {
      yiyan,
      deepseek,
      siliconflow,
      qwen,
      tiangong,
      openAI,
    }

    const provider = providers[data.model as keyof typeof providers] || openAI
    await provider(data, options)
  },
}

export default aiService
