import type { ChatTimelineMessageItem } from '@easyflow/common-ui';

const ANSWER_SEPARATOR = '\n\n';
const ANSWER_PART_SUFFIX = '-answer';

/**
 * 创建工作流 LLM 流式消息。
 *
 * @param id 消息 ID
 * @param nodeName 节点名称
 * @returns 待接收思考或回答增量的消息
 */
export function createWorkflowStreamMessage(
  id: string,
  nodeName: string,
): ChatTimelineMessageItem {
  return {
    id,
    parts: [
      {
        content: `**${nodeName}**`,
        id: `${id}${ANSWER_PART_SUFFIX}`,
        type: 'text',
      },
    ],
    role: 'assistant',
    status: 'streaming',
    type: 'message',
  };
}

/**
 * 以不可变方式追加流式文本，确保时间线子组件能够观察到消息引用变化。
 *
 * @param message 当前流式消息
 * @param delta 本次新增文本
 * @returns 追加文本后的新消息
 */
export function appendWorkflowStreamDelta(
  message: ChatTimelineMessageItem,
  delta: string,
): ChatTimelineMessageItem {
  const answerPartId = `${message.id}${ANSWER_PART_SUFFIX}`;
  return {
    ...message,
    parts: message.parts.map((part) => {
      if (part.type === 'thinking' && part.status === 'thinking') {
        return {
          ...part,
          status: 'end' as const,
        };
      }
      if (part.id === answerPartId && part.type === 'text') {
        const separator = part.content.includes(ANSWER_SEPARATOR)
          ? ''
          : ANSWER_SEPARATOR;
        return {
          ...part,
          content: `${part.content}${separator}${delta}`,
        };
      }
      return part;
    }),
  };
}

/**
 * 以不可变方式追加模型思考增量。
 *
 * @param message 当前流式消息
 * @param delta 本次新增思考内容
 * @returns 追加思考后的新消息；正式回答已开始时忽略迟到的思考片段
 */
export function appendWorkflowThinkingDelta(
  message: ChatTimelineMessageItem,
  delta: string,
): ChatTimelineMessageItem {
  const answerPartId = `${message.id}${ANSWER_PART_SUFFIX}`;
  const answerPart = message.parts.find(
    (part) => part.id === answerPartId && part.type === 'text',
  );
  if (answerPart?.content.includes(ANSWER_SEPARATOR)) {
    return message;
  }
  const thinkingPart = message.parts.find((part) => part.type === 'thinking');
  if (!thinkingPart) {
    return {
      ...message,
      parts: [
        {
          content: delta,
          id: `${message.id}-thinking`,
          status: 'thinking',
          type: 'thinking',
        },
        ...message.parts,
      ],
    };
  }
  return {
    ...message,
    parts: message.parts.map((part) =>
      part.id === thinkingPart.id && part.type === 'thinking'
        ? {
            ...part,
            content: `${part.content}${delta}`,
            status: 'thinking',
          }
        : part,
    ),
  };
}

/**
 * 以不可变方式更新流式消息状态。
 *
 * @param message 当前流式消息
 * @param status 新消息状态
 * @returns 更新状态后的新消息
 */
export function updateWorkflowStreamStatus(
  message: ChatTimelineMessageItem,
  status: ChatTimelineMessageItem['status'],
): ChatTimelineMessageItem {
  return {
    ...message,
    parts: message.parts.map((part) =>
      part.type === 'thinking'
        ? {
            ...part,
            status: status === 'error' ? 'error' : 'end',
          }
        : part,
    ),
    status,
  };
}
