/**
 * Gemini 并行 functionCall：执行顺序必须与 model parts 内 functionCall 顺序一致，
 * 否则 buildFunctionResponseUserTurn 回填会与云端请求错位，引发工具复读。
 */

import { extractFunctionCallsFromParts } from "./geminiContentStream.ts";

export type GeminiFunctionCallLike = {
  name?: string;
  args?: unknown;
  id?: string;
};

function asCall(raw: unknown): GeminiFunctionCallLike {
  return raw as GeminiFunctionCallLike;
}

/**
 * 以 model parts 为权威顺序；仅当 parts 无 FC 时回退 stream 聚合的 functionCalls。
 */
export function resolveOrderedFunctionCalls(
  modelParts: readonly unknown[],
  streamCalls: readonly unknown[],
): GeminiFunctionCallLike[] {
  const fromParts = extractFunctionCallsFromParts(modelParts).map(asCall);
  if (fromParts.length > 0) return fromParts;
  return streamCalls.map(asCall);
}

export function functionCallOrderMismatch(
  modelParts: readonly unknown[],
  streamCalls: readonly unknown[],
): boolean {
  const fromParts = extractFunctionCallsFromParts(modelParts).map(asCall);
  if (fromParts.length === 0 || streamCalls.length === 0) return false;
  if (fromParts.length !== streamCalls.length) return true;
  for (let i = 0; i < fromParts.length; i++) {
    const a = fromParts[i]!;
    const b = asCall(streamCalls[i]);
    if (String(a.name ?? "") !== String(b.name ?? "")) return true;
    const aid = a.id ?? "";
    const bid = b.id ?? "";
    if (aid && bid && aid !== bid) return true;
  }
  return false;
}
