import { defineStore } from 'pinia'
import { ref, watch } from 'vue'

export const useRagLabStore = defineStore('ragLab', () => {
  const query = ref(localStorage.getItem('ragLab_query') || '')
  const kbIds = ref<string[]>(JSON.parse(localStorage.getItem('ragLab_kbIds') || '[]'))
  const llmProvider = ref(localStorage.getItem('ragLab_llmProvider') || '')
  const topK = ref(parseInt(localStorage.getItem('ragLab_topK') || '3', 10))
  const scoreThreshold = ref(parseFloat(localStorage.getItem('ragLab_scoreThreshold') || '0.5'))
  const generateResponse = ref(localStorage.getItem('ragLab_generateResponse') !== 'false')
  const streamOutput = ref(localStorage.getItem('ragLab_streamOutput') === 'true')

  watch(query, (val) => localStorage.setItem('ragLab_query', val))
  watch(kbIds, (val) => localStorage.setItem('ragLab_kbIds', JSON.stringify(val)), { deep: true })
  watch(llmProvider, (val) => localStorage.setItem('ragLab_llmProvider', val))
  watch(topK, (val) => localStorage.setItem('ragLab_topK', String(val)))
  watch(scoreThreshold, (val) => localStorage.setItem('ragLab_scoreThreshold', String(val)))
  watch(generateResponse, (val) => localStorage.setItem('ragLab_generateResponse', String(val)))
  watch(streamOutput, (val) => localStorage.setItem('ragLab_streamOutput', String(val)))

  const clearParams = () => {
    query.value = ''
    kbIds.value = []
    llmProvider.value = ''
    topK.value = 3
    scoreThreshold.value = 0.5
    generateResponse.value = true
    streamOutput.value = false
  }

  return {
    query,
    kbIds,
    llmProvider,
    topK,
    scoreThreshold,
    generateResponse,
    streamOutput,
    clearParams
  }
})
