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

export interface ILLMSettings {
  provider: string
  model: string
  api_key: string
  base_url: string
}

export interface ISkillSettings {
  default_skill: string
  auto_routing: boolean
}

export interface IKBSettings {
  default_sources: string[]
  top_k: number
  retrieval_mode: string
}

export interface ISystemSettings {
  rate_limit: number
  cors_origins: string[]
  logging_level: string
}

const API_BASE = '/api/v1/settings'

export const useSettingsStore = defineStore('settings', () => {
  // --- State ---
  const llm = ref<ILLMSettings>({
    provider: '',
    model: '',
    api_key: '',
    base_url: '',
  })
  const skillSettings = ref<ISkillSettings>({
    default_skill: '',
    auto_routing: true,
  })
  const kbSettings = ref<IKBSettings>({
    default_sources: [],
    top_k: 5,
    retrieval_mode: 'standard',
  })
  const system = ref<ISystemSettings>({
    rate_limit: 60,
    cors_origins: ['*'],
    logging_level: 'INFO',
  })
  const isLoading = ref(false)
  const isSaving = ref(false)
  const error = ref<string | null>(null)
  const saveSuccess = ref(false)

  // --- Getters ---
  const hasLLMConfig = computed(() => !!llm.value.provider && !!llm.value.model)

  // --- Actions ---
  async function fetchSettings(): Promise<void> {
    isLoading.value = true
    error.value = null
    try {
      const res = await fetch(`${API_BASE}`)
      if (res.ok) {
        const data = await res.json()
        if (data.llm) Object.assign(llm.value, data.llm)
        if (data.skills) Object.assign(skillSettings.value, data.skills)
        if (data.knowledge) Object.assign(kbSettings.value, data.knowledge)
        if (data.system) Object.assign(system.value, data.system)
      }
    } catch (err) {
      // Settings endpoint may not exist yet, use defaults
      console.warn('Failed to fetch settings, using defaults:', err)
    } finally {
      isLoading.value = false
    }
  }

  async function saveSettings(): Promise<void> {
    isSaving.value = true
    error.value = null
    saveSuccess.value = false
    try {
      const res = await fetch(`${API_BASE}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          llm: llm.value,
          skills: skillSettings.value,
          knowledge: kbSettings.value,
          system: system.value,
        }),
      })
      if (!res.ok) {
        throw new Error(`保存失败: ${res.statusText}`)
      }
      saveSuccess.value = true
      setTimeout(() => {
        saveSuccess.value = false
      }, 3000)
    } catch (err) {
      error.value = err instanceof Error ? err.message : '保存设置失败'
      console.error('Failed to save settings:', err)
      throw err
    } finally {
      isSaving.value = false
    }
  }

  return {
    // State
    llm,
    skillSettings,
    kbSettings,
    system,
    isLoading,
    isSaving,
    error,
    saveSuccess,
    // Getters
    hasLLMConfig,
    // Actions
    fetchSettings,
    saveSettings,
  }
})
