/**
 * Chat API | 对话 API
 */

import { request } from '@/utils'

// 对话补全
export const chatCompletions = (data) =>
  request({
    url: `/chat/completions`,
    method: 'post',
    data
  })

// 流式对话补全
export const streamChatCompletions = async function* (data, signal, options = {}) {
  const text = data?.messages?.at?.(-1)?.content || data?.goal || ''
  const response = await fetch('/api/creative/copy', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ goal: typeof text === 'string' ? text : JSON.stringify(text), seconds: 15 }),
    signal
  })

  if (!response.ok) {
    const error = await response.json().catch(() => ({}))
    throw new Error(error?.detail || error?.message || '提示词助手请求失败')
  }

  const json = await response.json()
  const variant = json.variants?.[0]
  yield variant?.image_prompt_en || variant?.video_prompt_en || ''
}
