import { ref } from 'vue'
import { api } from '../api/client'

export function useAiSummary(pmid: number) {
  const aiLoading = ref(false)
  const aiSummary = ref('')
  const aiMode = ref('one_liner')

  // 尝试加载已缓存的 AI 摘要（按 mode 匹配）
  async function tryLoadCached() {
    try {
      const { data } = await api.get(`/ai/preview/${pmid}`)
      const summariesByMode = data?.summaries_by_mode || {}
      if (summariesByMode[aiMode.value]) {
        aiSummary.value = summariesByMode[aiMode.value]
      }
    } catch { /* ignore */ }
  }
  tryLoadCached()

  async function generateAI(mode: string) {
    aiMode.value = mode
    // 先查缓存
    try {
      const { data } = await api.get(`/ai/preview/${pmid}`)
      const summariesByMode = data?.summaries_by_mode || {}
      if (summariesByMode[mode]) {
        aiSummary.value = summariesByMode[mode]
        return
      }
    } catch { /* ignore */ }

    // 缓存未命中，调用生成
    aiLoading.value = true
    try {
      const { data } = await api.post(`/ai/generate/${pmid}?mode=${mode}`)
      aiSummary.value = data.summary
    } catch (e) {
      const axiosErr = e as { response?: { status?: number } }
      if (axiosErr.response?.status === 503) aiSummary.value = 'AI 服务暂不可用（需配置 OpenAI API Key），部署后即可自动生成。'
      else aiSummary.value = '生成失败，请重试。'
    } finally { aiLoading.value = false }
  }

  return { aiLoading, aiSummary, aiMode, generateAI }
}
