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 updateTransform(res: any): AIMessage | null {
  try {
    const message = JSON.parse(res)
    if (message.choices && message.choices.length > 0) {
      const delta = message.choices[0].delta
      return {
        id: message.id,
        role: 'assistant',
        content: delta.content || '',
        reasoning_content: delta.reasoning_content || '',
      }
    }
  } catch (error) {
    console.error(error)
  }
  return null
}

function successTransform(messages: AIMessage[]) {
  const result = messages.reduce(
    (acc, curr) => ({
      ...acc,
      content: acc.content + curr.content,
      reasoning_content: acc.reasoning_content + curr.reasoning_content,
    }),
    { content: '', reasoning_content: '' }
  )
  return { ...result, json: extractJSON(result.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 }),
    },
    updateTransform,
    successTransform
  )
}

// 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 }),
    },
    updateTransform,
    successTransform
  )
}

// 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 }),
    },
    updateTransform,
    successTransform
  )
}

// 通义千问
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 }),
    },
    updateTransform,
    successTransform
  )
}

// 天工
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 }),
    },
    updateTransform,
    successTransform
  )
}

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] || qwen
    await provider(data, options)
  },
}

export default aiService
