// src/constants/events.ts
import { getAgentTypeIcon } from '@/lib/agentUtils'
import { useAgentCatalogStore } from '@/store/agentCatalogStore'
import type { EventLogEntry } from '@/types/messages'
import DOMPurify from 'dompurify'

export interface EventDescriptor {
  label: string
  /** DKU icon CSS class, e.g. "dku-icon-lightbulb-16" */
  icon: string
  spin?: boolean
}

/**
 * Canonical mapping for server-side event kinds → UI descriptor.
 * Add new kinds here once and every component will pick them up.
 */
export const EVENT_MAPPING: Record<string, EventDescriptor> = {
  /* Chat streaming ------------------------------------------------- */
  AGENT_SELECTION: { label: 'Evaluating Agents', icon: 'dku-icon-arrow-circular-16', spin: true }, //
  AGENT_GETTING_READY: { label: '%sgetting ready', icon: 'dku-icon-ai-agent-16', spin: true },
  AGENT_THINKING: { label: '%sthinking…', icon: 'dku-icon-lightbulb-16', spin: true },
  AGENT_TOOL_START: { label: '%susing tool %s', icon: 'dku-icon-tool-wrench-16' },
  GENERATING_CHART: { label: 'Generating chart...', icon: 'dku-icon-chart-16' },
  chart_plan: { label: 'Chart generated', icon: 'dku-icon-chart-16' },
  chart_plan_error: { label: 'Chart generation failed', icon: 'dku-icon-error-16' },
  artifacts: { label: 'Downloads', icon: 'dku-icon-bundle-16', spin: false },
  CALLING_AGENT: { label: 'Calling %s', icon: 'dku-icon-ai-agent-16', spin: true },
  AGENT_CALLING_AGENT: { label: '%s calling %s', icon: 'dku-icon-ai-agent-16', spin: true },
  synthesizing_started: {
    label: 'Preparing final answer...',
    icon: 'dku-icon-arrow-circular-16',
    spin: true,
  },
  synthesizing_finished: { label: 'Completed', icon: 'dku-icon-checkmark-16', spin: true },
  agent_chunk: { label: '%sanswering...', icon: 'dku-icon-ai-agent-16', spin: true },
  agent_started: { label: 'Calling %s', icon: 'dku-icon-ai-agent-16', spin: true },
  agent_finished: { label: '%sdone', icon: 'dku-icon-checkmark-16', spin: true },
  answer_stream_start: {
    label: '%s responding...',
    icon: 'dku-icon-comment-multiple-16',
    spin: false,
  },
  agent_event: { label: '', icon: 'dku-icon-circular-16', spin: true },
  agent_error: { label: 'Agent error', icon: 'dku-icon-dismiss-16', spin: true },
  references: { label: 'Sources', icon: 'dku-icon-wiki-16', spin: false },

  /* Event-log panel ------------------------------------------------- */
  SEARCH_QUERY: { label: 'Searching…', icon: 'dku-icon-search-16', spin: true },

  /* Add future event kinds above this line -------------------------- */
  /* Trace events ---------------------------------------------------- */
  TRACE: { label: 'Trace', icon: 'dku-icon-circle-outline-16' },
}

/**
 * Canonical mapping for source types → readable labels.
 * Used in the References/Sources tab of the Event Log Panel.
 */
export const SOURCE_TYPE_LABELS: Record<string, string> = {
  // Standard types
  FILE_BASED_DOCUMENT: 'Document',
  SIMPLE_DOCUMENT: 'Document',
  RECORDS: 'Records',
  GENERATED_SQL_QUERY: 'Generated SQL Query',
  CODE_SNIPPET: 'Code Snippet',
  IMAGE: 'Image',
  INFO: 'Info',
}

/** Get readable label for source type */
export function getSourceTypeLabel(type?: string): string {
  if (!type) return ''
  return SOURCE_TYPE_LABELS[type] || type
}

/** Safe accessor used by the UI */
export function getEventInfo(kind: string, vals?: string[]): Omit<EventDescriptor, 'icon'> {
  let label = EVENT_MAPPING[kind]?.label || kind
  for (const placeholderVal of vals || []) {
    label = label.replace(`%s`, placeholderVal ? placeholderVal + ' ' : '')
  }
  const spin = EVENT_MAPPING[kind]?.spin
  return { label, spin }
}

export function getEventIcon(evt: EventLogEntry): string {
  // Only apply agent-specific icon logic for a specific set of events
  if (evt.eventKind === 'CALLING_AGENT' || evt.eventKind === 'agent_started') {
    const agentId = evt.eventData?.agentId
    const agent = useAgentCatalogStore().getAgentById(agentId)
    if (agentId && agent) {
      return getAgentTypeIcon(agent)
    } else {
      return 'dku-icon-ai-agent-16'
    }
  }

  // For all other events, fall back to EVENT_MAPPING icon
  return EVENT_MAPPING[evt.eventKind]?.icon || 'dku-icon-info-16'
}

export function getEventInfoAsHtml(kind: string, vals?: string[]): EventDescriptor {
  let label = EVENT_MAPPING[kind]?.label || kind
  for (const placeholderVal of vals || []) {
    if (!placeholderVal) continue
    label = DOMPurify.sanitize(label.replace(`%s`, `<b>${placeholderVal || ''} </b>`))
  }
  const icon = EVENT_MAPPING[kind]?.icon || 'dku-icon-info-16'
  const spin = EVENT_MAPPING[kind]?.spin
  return { label, icon, spin }
}

export function getEventInfoStatic(kind: string): Omit<EventDescriptor, 'icon'> {
  const info = getEventInfo(kind)
  return { ...info, spin: false }
}

export const formatEvtValue = (value: any, key: string | number): string => {
  console.log('formatEvtValue', { value, key })
  if (typeof value === 'string' && key === 'toolName') {
    return value.split('_').slice(0, -1).join(' ')
  }
  if (typeof value === 'string' && key === 'agentAsToolName') {
    return value.split('_').join(' ')
  }
  return value
}
