import { defineStore } from 'pinia'
import { ref } from 'vue'
import { API } from '@/Api'
import type { UIConfig } from '@/types/conf'

interface LlmBrief {
  id: string
  name: string
  shortName: string
}
export const usePrefStore = defineStore('prefs', () => {
  const llms = ref<LlmBrief[]>([])
  const aHLlms = ref<LlmBrief[]>([])
  const embeddingLlms = ref<LlmBrief[]>([])
  const baseLlmid = ref<string>('')
  const baseEmbeddingLlmId = ref<string>('')
  const loading = ref(false)
  const loaded = ref(false)
  const uiConf = ref<UIConfig>()
  const favoriteAgents = ref<Record<string, boolean>>({})
  const showChatExamples = ref<boolean>(true)
  async function load() {
    if (loading.value || loaded.value) return
    loading.value = true
    try {
      const resp = await API.getLlms()
      llms.value = resp.data.llms
      aHLlms.value = (await API.getLlms()).data.ah_llms
      embeddingLlms.value = resp.data.embedding_llms
      const prefsRes = await API.getPreferences()
      baseLlmid.value = prefsRes.data.baseLlmid || (llms.value?.length ? llms.value[0]?.id : '')
      baseEmbeddingLlmId.value =
        prefsRes.data.baseEmbeddingLlmId ||
        (embeddingLlms.value?.length ? embeddingLlms.value[0]?.id : '')
      favoriteAgents.value = prefsRes.data.favorite || {}
      showChatExamples.value = prefsRes.data.showChatExamples ?? true
      uiConf.value = (await API.getUIConfig()).data
      loaded.value = true
    } finally {
      loading.value = false
    }
  }

  async function setBaseLlmid(id: string) {
    if (id === baseLlmid.value) return
    baseLlmid.value = id
    await API.updatePreferences({ baseLlmid: id })
  }

  async function setBaseEmbeddingLlmId(id: string) {
    if (id === baseEmbeddingLlmId.value) return
    baseEmbeddingLlmId.value = id
    await API.updatePreferences({ baseEmbeddingLlmId: id })
  }

  async function toggleFavoriteAgent(agentId: string, isFavorite: boolean) {
    if (isFavorite) {
      favoriteAgents.value[agentId] = isFavorite
    } else {
      delete favoriteAgents.value[agentId]
    }
    await API.updatePreferences({ favorite: favoriteAgents.value })
  }

  async function setShowChatExamples(value: boolean) {
    if (value === showChatExamples.value) return
    showChatExamples.value = value
    await API.updatePreferences({ showChatExamples: value })
  }

  async function reload() {
    loaded.value = false
    await load()
  }

  return {
    llms,
    embeddingLlms,
    baseLlmid,
    aHLlms,
    baseEmbeddingLlmId,
    uiConf,
    favoriteAgents,
    showChatExamples,
    load,
    reload,
    setBaseLlmid,
    setBaseEmbeddingLlmId,
    toggleFavoriteAgent,
    setShowChatExamples,
  }
})
