import type { IRawStepTask, IRichText } from '@/stores'

function nameJoin(names: string[]): string {
  // join names with comma, and 'and' for the last one
  const tmp = [...names]
  const last = tmp.pop()!
  let t = tmp.join(', ')
  if (t.length > 0) {
    t = `${t} 和 ${last}`
  } else {
    t = last
  }
  return t
}

export function changeBriefs(task?: IRawStepTask[]): IRawStepTask[] {
  if (!task) {
    return []
  }
  return task.map((item) => {
    const record = {
      ...item,
      Collaboration_Brief_frontEnd: changeBrief(item),
    }
    return record
  })
}

function changeBrief(task: IRawStepTask): IRichText {
  // 如果不存在AgentSelection直接返回
  const agents = task.AgentSelection ?? []
  if (agents.length === 0) {
    return task.Collaboration_Brief_frontEnd
  }
  const data: IRichText['data'] = {}
  let indexOffset = 0

  // 根据InputObject_List修改
  const inputs = task.InputObject_List ?? []
  const inputPlaceHolders = inputs.map((text, index) => {
    data[(index + indexOffset).toString()] = {
      text,
      style: { background: '#ACDBA0' },
    }
    return `!<${index + indexOffset}>!`
  })
  const inputSentence = nameJoin(inputPlaceHolders)
  indexOffset += inputs.length

  // 根据AgentSelection修改
  const namePlaceholders = agents.map((text, index) => {
    data[(index + indexOffset).toString()] = {
      text,
      style: { background: '#E5E5E5', boxShadow: '1px 1px 4px 1px #0003' },
    }
    return `!<${index + indexOffset}>!`
  })
  const nameSentence = nameJoin(namePlaceholders)
  indexOffset += agents.length

  let actionSentence = task.TaskContent ?? ''

  // delete the last '.' of actionSentence
  if (actionSentence[actionSentence.length - 1] === '.') {
    actionSentence = actionSentence.slice(0, -1)
  }
  const actionIndex = indexOffset++

  data[actionIndex.toString()] = {
    text: actionSentence,
    style: { background: '#DDD', border: '1.5px solid #ddd' },
  }

  let outputSentence = ''
  const output = task.OutputObject ?? ''
  if (output) {
    data[indexOffset.toString()] = {
      text: output,
      style: { background: '#FFCA8C' },
    }
    outputSentence = `得到 !<${indexOffset}>!`
  }

  // Join them togeter
  let content = inputSentence
  if (content) {
    content = `基于${content}, ${nameSentence} 执行任务 !<${actionIndex}>!`
  } else {
    content = `${nameSentence} 执行任务 !<${actionIndex}>!`
  }
  if (outputSentence) {
    content = `${content}, ${outputSentence}.`
  } else {
    content = `${content}.`
  }
  content = content.trim()

  return {
    template: content,
    data,
  }
}
