export function coalesceEvents(events) {
  return events.reduce((result, item) => appendEvent(result, item), []);
}

export function appendEvent(events, item) {
  const previous = events.at(-1);
  if (isAssistantDelta(previous) && isAssistantDelta(item)) {
    return [
      ...events.slice(0, -1),
      {
        ...previous,
        data: {
          ...previous.data,
          text: `${previous.data.text}${item.data.text}`
        }
      }
    ];
  }
  return [...events, item];
}

function isAssistantDelta(item) {
  return item?.event === "session.output" && item.data?.kind === "assistant_delta";
}
