// Shared task-status helpers. Used by the Overview homepage (and previously the
// standalone Tasks board) to map a session's lifecycle onto a small set of
// display buckets, styles, and filters.
import type { Session } from '$lib/api'

export type Bucket = 'running' | 'input' | 'done' | 'failed'

export function bucket(s: Session): Bucket {
  switch (s.status) {
    case 'awaiting_input':
      return 'input'
    case 'done':
      return s.outcome === 'failure' ? 'failed' : 'done'
    case 'failed':
      return 'failed'
    default:
      return 'running' // active | planning | executing | undefined
  }
}

export interface StatusStyle {
  label: string
  dot: string
  pulse: boolean
}

export function statusStyle(s: Session): StatusStyle {
  switch (bucket(s)) {
    case 'input':
      return { label: 'Needs input', dot: 'bg-warning', pulse: true }
    case 'done':
      return {
        label: s.outcome === 'partial' ? 'Done · partial' : 'Done',
        dot: 'bg-success',
        pulse: false
      }
    case 'failed':
      return { label: 'Failed', dot: 'bg-destructive', pulse: false }
    default:
      return { label: 'Running', dot: 'bg-primary', pulse: true }
  }
}

export const FILTERS: { id: 'all' | Bucket; label: string }[] = [
  { id: 'all', label: 'All' },
  { id: 'running', label: 'Running' },
  { id: 'input', label: 'Needs input' },
  { id: 'done', label: 'Done' },
  { id: 'failed', label: 'Failed' }
]

// Task events that should trigger a session-board refetch.
export const TASK_EVENTS = new Set([
  'task.status',
  'goal.set',
  'question.raised',
  'question.answered'
])

export function heading(s: Session): string {
  return s.goal || s.title || 'Untitled task'
}
