import { defineStore } from 'pinia'
import { toast } from '../utils/toast.js'
import { ref, computed } from 'vue'
import { useApi } from '../composables/useApi.js'

export const useImportStore = defineStore('import', () => {
  const api = useApi()

  const settings = ref(null)
  const settingsLoading = ref(false)
  const settingsError = ref(null)

  const activeBatch = ref(null)
  const statusLoading = ref(false)

  const tasks = ref([])
  const tasksNextCursor = ref(null)
  const tasksLoading = ref(false)
  const tasksFilter = ref({ status: null, limit: 50 })

  const triggerError = ref(null)

  async function loadSettings() {
    settingsLoading.value = true
    settingsError.value = null
    try {
      settings.value = await api.get('/api/settings/import')
    } catch (e) {
      settingsError.value = e.message
    } finally {
      settingsLoading.value = false
    }
  }

  async function patchSettings(patch) {
    settingsError.value = null
    try {
      settings.value = await api.patch('/api/settings/import', { body: patch })
    } catch (e) {
      settingsError.value = e.message
      toast({ text: `Settings save failed: ${e.message}`, type: 'error' })
      throw e
    }
  }

  async function refreshStatus() {
    statusLoading.value = true
    try {
      const body = await api.get('/api/import/status')
      activeBatch.value = body.active_batch
    } finally {
      statusLoading.value = false
    }
  }

  async function triggerScan(mode = 'quick') {
    if (!['quick', 'deep', 'verify'].includes(mode)) {
      throw new Error(`unsupported scan mode: ${mode}`)
    }
    triggerError.value = null
    try {
      await api.post('/api/import/trigger', { body: { mode } })
      // Acknowledge immediately so the click isn't invisible. scan_directory
      // can finalize the batch synchronously when every file in /import is
      // already on a non-failed ImportTask (operator-flagged 2026-05-25:
      // 233k existing tasks → all paths in skip-set → files_seen=0 →
      // batch flashes 'running' for <100ms then 'complete' before the
      // first refreshStatus() lands; UI never sees the active state).
      const label = mode === 'deep'
        ? 'Deep scan triggered (re-applying sidecar metadata + filling NULL phash/artist on existing rows)'
        : mode === 'verify' ? 'Library verify triggered' : 'Quick scan triggered'
      toast({ text: label, type: 'success' })
      await refreshStatus()
      // Re-poll twice over ~5s and produce an HONEST follow-up toast.
      // Operator-flagged 2026-05-25: the prior "no new files" message was
      // misleading because deep scan IS doing work (refresh) even when
      // there are no new files to import. Surface the real workload count
      // (imported + refreshed + queued) instead. For quick scan + zero
      // queued work, fall back to "up to date" instead of the old
      // implementation-detail-leaking message.
      setTimeout(async () => {
        await refreshStatus()
        await loadTasks(true)
        if (activeBatch.value || mode === 'verify') return
        // Batch finalized quickly; figure out what actually happened.
        // The task list was just refreshed; the freshest row(s) carry
        // the batch outcome.
        const batchId = tasks.value[0]?.batch_id
        const sameBatch = batchId
          ? tasks.value.filter(t => t.batch_id === batchId)
          : []
        const refreshedCount = sameBatch.filter(t => t.status === 'complete' && t.result_image_id).length
        const newImported = sameBatch.filter(t => t.status === 'complete' && t.result_image_id && !t.error).length
        if (mode === 'deep' && sameBatch.length > 0) {
          toast({
            text: `Deep scan finished — ${sameBatch.length} file(s) processed`,
            type: 'info',
          })
        } else if (mode === 'quick' && sameBatch.length > 0) {
          toast({
            text: `Quick scan finished — ${newImported} new file(s) queued`,
            type: 'info',
          })
        } else {
          toast({ text: 'Library is up to date', type: 'info' })
        }
      }, 2000)
    } catch (e) {
      triggerError.value = e.message
      toast({ text: `Scan failed: ${e.message}`, type: 'error' })
      throw e
    }
  }

  async function loadTasks(reset = true) {
    tasksLoading.value = true
    try {
      const params = { limit: tasksFilter.value.limit }
      if (tasksFilter.value.status) params.status = tasksFilter.value.status
      if (!reset && tasksNextCursor.value) params.cursor = tasksNextCursor.value
      const body = await api.get('/api/import/tasks', { params })
      tasks.value = reset ? body.tasks : [...tasks.value, ...body.tasks]
      tasksNextCursor.value = body.next_cursor
    } finally {
      tasksLoading.value = false
    }
  }

  function setStatusFilter(status) {
    tasksFilter.value.status = status
  }

  async function retryFailed() {
    await api.post('/api/import/retry-failed')
    await loadTasks(true)
  }

  async function clearCompleted(ageDays = 0) {
    await api.post('/api/import/clear-completed', { body: { age_days: ageDays } })
    await loadTasks(true)
  }

  async function clearStuck() {
    const body = await api.post('/api/import/clear-stuck')
    await loadTasks(true)
    await refreshStatus()
    return body
  }

  // Layer-2 one-shot re-download for a failed task's (corrupt) file.
  // Returns the endpoint's status dict (refetch_queued / no_source /
  // already_refetched). Caller surfaces it as a toast.
  async function refetchTask(taskId) {
    const body = await api.post(`/api/import/tasks/${taskId}/refetch`)
    await loadTasks(true)
    return body
  }

  const hasMore = computed(() => tasksNextCursor.value !== null)

  return {
    settings, settingsLoading, settingsError,
    activeBatch, statusLoading,
    tasks, tasksLoading, tasksFilter, hasMore,
    triggerError,
    loadSettings, patchSettings,
    refreshStatus, triggerScan,
    loadTasks, setStatusFilter, retryFailed, clearCompleted, clearStuck,
    refetchTask,
  }
})
