import type { InboxItemDot } from '@overdeck/deck-ui'
import { sortItemsBySeverity } from '../../lib/overview-mappers'
import type { Item, Kind, Severity } from '../../lib/collector-types'

export const ALL_KINDS: readonly Kind[] = ['alert', 'ci', 'halt', 'decision', 'limit', 'gate', 'progress', 'build']

const DOT_FOR_SEVERITY: Record<Severity, InboxItemDot> = { act: 'red', warn: 'amber', info: 'blue' }

export function severityDotFor(severity: Severity): InboxItemDot {
  return DOT_FOR_SEVERITY[severity]
}

/** act > warn > info, then most-recent ts first — full inbox triage order. */
export function sortInboxItems(items: Item[]): Item[] {
  return sortItemsBySeverity(items)
}

export function kindCounts(items: Item[]): Record<Kind, number> {
  const counts = Object.fromEntries(ALL_KINDS.map((kind) => [kind, 0])) as Record<Kind, number>
  for (const item of items) counts[item.kind] += 1
  return counts
}

export function isDecisionAnswerAction(item: Item, action: { verb: string; label: string }): boolean {
  if (item.kind !== 'decision' && item.kind !== 'halt') return false
  return action.verb === 'answer' || action.label.toLowerCase() === 'answer'
}

/** HALT/decision rows always expose a live Answer affordance per the U2 contract. */
export function triageActionsFor(item: Item): Item['actions'] {
  if (item.kind !== 'halt' && item.kind !== 'decision') return item.actions
  if (item.actions.some((action) => isDecisionAnswerAction(item, action))) return item.actions
  return [{ verb: 'answer', args: {}, label: 'Answer', recommended: true }, ...item.actions]
}

export const WAVE4_ACTION_TOOLTIP = 'Actions land in wave 4'
