import { Message } from "../../../types/message";

export const processRetryLogic = (
  messages: Message[],
): { availableData: Message[]; invalidBranches: Message[][] } => {
  const invalidBranches: Message[][] = [];
  const parentLastIndexMap = new Map<number, number>();
  const invalidIndices = new Set<number>();

  messages.forEach((msg, index) => {
    const pSeq = msg.parent_sequence;
    if (typeof pSeq === "number") {
      if (parentLastIndexMap.has(pSeq)) {
        const lastIndex = parentLastIndexMap.get(pSeq)!;
        // 提取失效分支：从上一次出现位置到当前位置之前
        const invalidBranch = messages.slice(lastIndex, index);
        if (invalidBranch.length > 0) {
          invalidBranches.push(invalidBranch);
          for (let k = lastIndex; k < index; k++) {
            invalidIndices.add(k);
          }
        }
        parentLastIndexMap.set(pSeq, index);
      } else {
        parentLastIndexMap.set(pSeq, index);
      }
    }
  });

  const availableData = messages.filter((_, index) => !invalidIndices.has(index));
  return { availableData, invalidBranches };
};
