export interface TaskAgentOption {
  id: string
  label: string
}

interface LiveAgentOptionSource {
  id: string
  name: string
}

/**
 * OpenClaw supplies the live inventory. Nexus adds only local assignment
 * concepts plus values already persisted on visible tasks, so a disconnected
 * gateway never makes the current value disappear from a select.
 */
export function buildTaskAgentOptions(
  liveAgents: readonly LiveAgentOptionSource[],
  persistedValues: readonly (string | null | undefined)[] = [],
): TaskAgentOption[] {
  const options = new Map<string, TaskAgentOption>()
  const add = (id: string, label: string) => {
    const normalizedId = id.trim()
    const key = normalizedId.toLocaleLowerCase()
    if (!options.has(key)) {
      options.set(key, {
        id: normalizedId,
        label: label.trim() || normalizedId,
      })
    }
  }

  add('', 'Nicht zugewiesen')
  add('bao', 'Bao')
  for (const agent of liveAgents) add(agent.id, agent.name)
  for (const value of persistedValues) {
    if (value?.trim()) add(value, value)
  }

  return [...options.values()]
}

export function taskAgentLabel(
  value: string | null | undefined,
  options: readonly TaskAgentOption[],
): string {
  if (!value) return ''
  const normalized = value.toLocaleLowerCase()
  return options.find(option => option.id.toLocaleLowerCase() === normalized)?.label
    ?? value
}
