import axios from 'axios'
import md5 from 'blueimp-md5'
import { AIMessage, ChatRequestData, GenerateImageRequestData, GenerateVideoRequestData } from './types'
import { request, RequestOptions } from './request'

function transform(message: any): AIMessage | null {
  if (message.choices && message.choices.length > 0) {
    const delta = message.choices[0].delta
    return {
      role: 'assistant',
      reasoning_content: delta.reasoning_content,
      content: delta.content,
    }
  }
  return null
}

// 文心一言
export async function chatBaidu(data: ChatRequestData, options: RequestOptions) {
  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 request(
    `/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 chatDeepSeek(data: ChatRequestData, options: RequestOptions) {
  await request(
    '/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 chatSiliconFlow(data: ChatRequestData, options: RequestOptions) {
  if (data.model === 'Qwen/QwQ-32B') {
    delete data.response_format
  }
  await request(
    '/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 chatQwen(data: ChatRequestData, options: RequestOptions) {
  await request(
    '/api/qwen/compatible-mode/v1/chat/completions',
    {
      ...options,
      headers: { 'Content-Type': 'application/json', Authorization: 'Bearer sk-afd0fcdb53bf4058b2068b8548820150' },
      body: JSON.stringify({ ...data, model: 'qwen-max-latest', stream: true }),
    },
    transform
  )
}

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

  await request('/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 chatCreate(data: ChatRequestData, options: RequestOptions) {
  if (data.model === 'Qwen/QwQ-32B') {
    delete data.response_format
  }
  await request(
    '/api/openai/chat/create',
    {
      ...options,
      headers: { 'Content-Type': 'application/json', Authorization: 'ezijing@20250331' },
      body: JSON.stringify({ stream: true, ...data }),
    },
    transform
  )
}

// 文生图
export async function imageCreate(data: GenerateImageRequestData, options: RequestOptions) {
  const resp = await request(
    '/api/openai/image/create',
    {
      ...options,
      headers: { 'Content-Type': 'application/json', Authorization: 'ezijing@20250331' },
      body: JSON.stringify({ ...data, model: 'image-01' }),
    },
    (response) => {
      return { ...response.data, content: '图片生成成功' }
    }
  )
  return resp
}

// 文生视频
export async function videoCreate(data: GenerateVideoRequestData, options: RequestOptions) {
  const resp = await request('/api/openai/video/create', {
    ...options,
    headers: { 'Content-Type': 'application/json', Authorization: 'ezijing@20250331' },
    body: JSON.stringify(data),
  })
  return resp
}

const aiService = {
  async post(data: any, options: RequestOptions, method?: string) {
    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 = {
      chatBaidu,
      chatDeepSeek,
      chatSiliconFlow,
      chatQwen,
      chatTiangong,
      chatCreate,
      imageCreate,
      videoCreate,
    }

    const provider = providers[method as keyof typeof providers] || chatCreate
    await provider(data, options)
  },
}

export default aiService
