import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { isLocal as checkIsLocal } from '@/lib/utils'
import { configApi } from '@/api'
import type { AppConfig, DSSLLM } from '@/types'

export const useAppStore = defineStore('app', () => {
  // State
  const mode = ref<'local' | 'dss' | 'unknown'>('unknown')
  const isDarkMode = ref(false)

  // App configuration from backend
  const appConfig = ref<AppConfig | null>(null)
  const configError = ref(false)
  const configLoading = ref(false)

  // Shared LLM selections (session-scoped)
  const selectedLlmId = ref('')
  const selectedEmbeddingLlmId = ref('')

  // Getters
  const isLocal = computed(() => mode.value === 'local')
  const isDSS = computed(() => mode.value === 'dss')
  const version = computed(() => appConfig.value?.version ?? '0.1.0')
  const projectKey = computed(() => appConfig.value?.project_key ?? '')
  const semanticModelId = computed(() => appConfig.value?.semantic_model_id ?? '')

  // Actions
  function initializeApp() {
    mode.value = checkIsLocal() ? 'local' : 'dss'
    loadDarkMode()
  }

  async function loadConfig() {
    // Idempotent: skip if already loaded or loading
    if (appConfig.value || configLoading.value) {
      return
    }
    configLoading.value = true
    configError.value = false
    try {
      appConfig.value = await configApi.get()
    } catch (e) {
      console.error('Failed to load app config:', e)
      configError.value = true
    } finally {
      configLoading.value = false
    }
  }

  function toggleDarkMode() {
    isDarkMode.value = !isDarkMode.value
    if (isDarkMode.value) {
      document.documentElement.classList.add('dark')
      localStorage.setItem('darkMode', 'true')
    } else {
      document.documentElement.classList.remove('dark')
      localStorage.setItem('darkMode', 'false')
    }
  }

  function loadDarkMode() {
    const stored = localStorage.getItem('darkMode')
    if (stored === 'true') {
      isDarkMode.value = true
      document.documentElement.classList.add('dark')
    }
  }

  function setSelectedLlmId(id: string) {
    selectedLlmId.value = id
  }

  function setSelectedEmbeddingLlmId(id: string) {
    selectedEmbeddingLlmId.value = id
  }

  function ensureDefaultLlm(available: DSSLLM[]) {
    if (available.length === 0) {
      return
    }
    const current = selectedLlmId.value
    const exists = current && available.some((llm) => llm.id === current)
    if (exists) {
      return
    }
    const fallback = available[0].id
    selectedLlmId.value = fallback
  }

  return {
    // State
    mode,
    isDarkMode,
    appConfig,
    configError,

    // Getters
    isLocal,
    isDSS,
    version,
    projectKey,
    semanticModelId,
    selectedLlmId,
    selectedEmbeddingLlmId,

    // Actions
    initializeApp,
    loadConfig,
    toggleDarkMode,
    loadDarkMode,
    setSelectedLlmId,
    setSelectedEmbeddingLlmId,
    ensureDefaultLlm,
  }
})
