/**
 * OCR Settings Store
 *
 * Manages user's OCR engine preference and metrics.
 * - Auto-loads user's preferred engine on mount
 * - Saves preference to backend on change
 * - Provides OCR metrics for dashboard
 */

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '@data-entry/services/api'

export const useOCRSettingsStore = defineStore('ocrSettings', () => {
  // State
  const preferredEngine = ref('doctr_plus')
  // Available engines
  // NOTE: This default list is overwritten by loadPreference() from backend
  // Backend filters engines based on OCR_ENABLE_PADDLEOCR and OCR_ENABLE_TESSERACT
  const availableEngines = ref([
    'tesseract',
    'doctr',
    'doctr_plus',   // Recommended: 2-tier sequential with early exit
    'paddleocr',
  ])
  const loading = ref(false)
  const error = ref(null)
  const initialized = ref(false)

  // Metrics state
  const metrics = ref({
    summary: [],
    stats: null,
    history: [],
    historyTotal: 0,
  })
  const metricsLoading = ref(false)

  // Computed
  const isLoading = computed(() => loading.value)
  const hasError = computed(() => !!error.value)

  // Actions
  async function loadPreference() {
    if (initialized.value) return

    loading.value = true
    error.value = null

    try {
      const response = await api.get('/settings/ocr-preference')
      preferredEngine.value = response.data.preferred_engine
      availableEngines.value = response.data.available_engines
      initialized.value = true
      console.log('[OCRSettings] Loaded preference:', preferredEngine.value)
    } catch (err) {
      console.error('[OCRSettings] Failed to load preference:', err)
      error.value = err.message
      // Use defaults on error
      preferredEngine.value = 'doctr_plus'
    } finally {
      loading.value = false
    }
  }

  async function setPreference(engine) {
    loading.value = true
    error.value = null

    try {
      const response = await api.post('/settings/ocr-preference', {
        preferred_engine: engine
      })
      preferredEngine.value = response.data.preferred_engine
      console.log('[OCRSettings] Saved preference:', preferredEngine.value)
    } catch (err) {
      console.error('[OCRSettings] Failed to save preference:', err)
      error.value = err.message
      throw err
    } finally {
      loading.value = false
    }
  }

  async function loadMetricsSummary(days = 30) {
    metricsLoading.value = true

    try {
      const response = await api.get('/metrics/ocr/summary', { params: { days } })
      metrics.value.summary = response.data
      console.log('[OCRSettings] Loaded metrics summary:', metrics.value.summary.length, 'engines')
    } catch (err) {
      console.error('[OCRSettings] Failed to load metrics summary:', err)
    } finally {
      metricsLoading.value = false
    }
  }

  async function loadMetricsStats(days = 30) {
    try {
      const response = await api.get('/metrics/ocr/stats', { params: { days } })
      metrics.value.stats = response.data
      console.log('[OCRSettings] Loaded metrics stats:', metrics.value.stats)
    } catch (err) {
      console.error('[OCRSettings] Failed to load metrics stats:', err)
    }
  }

  async function loadMetricsHistory(limit = 50, offset = 0) {
    try {
      const response = await api.get('/metrics/ocr/history', { params: { limit, offset } })
      metrics.value.history = response.data.items
      metrics.value.historyTotal = response.data.total
      console.log('[OCRSettings] Loaded metrics history:', metrics.value.history.length, 'items')
    } catch (err) {
      console.error('[OCRSettings] Failed to load metrics history:', err)
    }
  }

  async function loadAllMetrics(days = 30) {
    metricsLoading.value = true
    try {
      await Promise.all([
        loadMetricsSummary(days),
        loadMetricsStats(days),
        loadMetricsHistory(20),
      ])
    } finally {
      metricsLoading.value = false
    }
  }

  // Reset state
  function $reset() {
    preferredEngine.value = 'doctr_plus'
    availableEngines.value = [
      'tesseract', 'doctr', 'doctr_plus', 'paddleocr',
    ]
    loading.value = false
    error.value = null
    initialized.value = false
    metrics.value = {
      summary: [],
      stats: null,
      history: [],
      historyTotal: 0,
    }
  }

  return {
    // State
    preferredEngine,
    availableEngines,
    loading,
    error,
    initialized,
    metrics,
    metricsLoading,

    // Computed
    isLoading,
    hasError,

    // Actions
    loadPreference,
    setPreference,
    loadMetricsSummary,
    loadMetricsStats,
    loadMetricsHistory,
    loadAllMetrics,
    $reset,
  }
})
