import { useQuery } from '@tanstack/react-query'
import { library, type WorkerStatus } from '../services/api'

interface ScanStatus {
  is_scanning: boolean
  current_folder?: string
  processed_files: number
  total_files: number
  errors: string[]
}

/** Pending tasks waiting in a queue. We deliberately ignore worker
 *  `active`/`reserved` counts here because they can stay non-zero
 *  briefly after a queue drains (workers hold prefetched tasks) and
 *  would otherwise leave the spinner running with nothing to do. */
function pendingTasks(ws: WorkerStatus | undefined): number {
  if (!ws) return 0
  return Object.values(ws.queues ?? {}).reduce((a, b) => a + b, 0)
}

/** Tasks actively being executed by workers right now. Distinct from
 *  pendingTasks so we can drop the spinner the moment no real work is
 *  in flight, even if reserved tasks linger. */
function activeTasks(ws: WorkerStatus | undefined): number {
  if (!ws) return 0
  return (
    ws.workers?.reduce((sum, w) => sum + (w.active ?? 0), 0) ?? 0
  )
}

/**
 * Read the current background-activity status (filesystem scan +
 * processing queues) so consumers can render a small inline spinner
 * instead of the old bottom-right popover. Shares query keys with
 * ScanProgress so polling stays deduplicated.
 */
export function useScanActivity() {
  const { data: scanStatus } = useQuery<ScanStatus>({
    queryKey: ['scan-status'],
    queryFn: () => library.scanStatus(),
    refetchInterval: (query) =>
      query.state.data?.is_scanning ? 2000 : 10000,
  })
  const { data: workerStatus } = useQuery<WorkerStatus>({
    queryKey: ['worker-status-progress'],
    queryFn: () => library.maintenance.workerStatus(),
    refetchInterval: (query) => {
      const data = query.state.data
      return pendingTasks(data) + activeTasks(data) > 0 ? 3000 : 15000
    },
  })

  const isScanning = scanStatus?.is_scanning ?? false
  const isProcessing =
    pendingTasks(workerStatus) + activeTasks(workerStatus) > 0

  return {
    active: isScanning || isProcessing,
    isScanning,
    isProcessing,
    /** Path of the folder currently being scanned, when known. */
    currentFolder: scanStatus?.current_folder ?? null,
  }
}
