import { isInstructions } from "../chat_context.js";
import { serializeImage } from "../utils.js";
import { groupToolCalls } from "./utils.js";
const EXTRA_CONTENT_KEYS = ["google", "livekit", "xai"];
function filterExtra(extra) {
  const filtered = {};
  for (const key of EXTRA_CONTENT_KEYS) {
    if (extra[key]) {
      filtered[key] = extra[key];
    }
  }
  return filtered;
}
async function toChatCtx(chatCtx, injectDummyUserMessage = true) {
  const itemGroups = groupToolCalls(chatCtx);
  const messages = [];
  for (const group of itemGroups) {
    if (group.isEmpty) continue;
    const message = group.message ? await toChatItem(group.message) : { role: "assistant" };
    const toolCalls = group.toolCalls.map((toolCall) => {
      const tc = {
        type: "function",
        id: toolCall.callId,
        function: { name: toolCall.name, arguments: toolCall.args }
      };
      const extraContent = toolCall.extra ? filterExtra(toolCall.extra) : {};
      if (!extraContent.google && toolCall.thoughtSignature) {
        extraContent.google = { thoughtSignature: toolCall.thoughtSignature };
      }
      if (Object.keys(extraContent).length > 0) {
        tc.extra_content = extraContent;
      }
      return tc;
    });
    if (toolCalls.length > 0) {
      message["tool_calls"] = toolCalls;
    }
    messages.push(message);
    for (const toolOutput of group.toolOutputs) {
      messages.push(await toChatItem(toolOutput));
    }
  }
  return messages;
}
async function toChatItem(item) {
  if (item.type === "message") {
    const listContent = [];
    let textContent = "";
    for (const content of item.content) {
      if (typeof content === "string") {
        if (textContent) textContent += "\n";
        textContent += content;
      } else if (isInstructions(content)) {
        if (textContent) textContent += "\n";
        textContent += content.value;
      } else if (content.type === "image_content") {
        listContent.push(await toImageContent(content));
      } else {
        throw new Error(`Unsupported content type: ${content.type}`);
      }
    }
    const result = { role: item.role };
    if (listContent.length === 0) {
      result.content = textContent;
    } else {
      if (textContent.length > 0) {
        listContent.push({ type: "text", text: textContent });
      }
      result.content = listContent;
    }
    if (item.extra) {
      const extraContent = filterExtra(item.extra);
      if (Object.keys(extraContent).length > 0) {
        result.extra_content = extraContent;
      }
    }
    return result;
  } else if (item.type === "function_call") {
    const tc = {
      id: item.callId,
      type: "function",
      function: { name: item.name, arguments: item.args }
    };
    const extraContent = item.extra ? filterExtra(item.extra) : {};
    if (!extraContent.google && item.thoughtSignature) {
      extraContent.google = { thoughtSignature: item.thoughtSignature };
    }
    if (Object.keys(extraContent).length > 0) {
      tc.extra_content = extraContent;
    }
    return {
      role: "assistant",
      tool_calls: [tc]
    };
  } else if (item.type === "function_call_output") {
    return {
      role: "tool",
      tool_call_id: item.callId,
      content: item.output
    };
  }
  throw new Error(`Unsupported item type: ${item["type"]}`);
}
async function toImageContent(content) {
  const cacheKey = "serialized_image";
  let serialized;
  if (content._cache[cacheKey] === void 0) {
    serialized = await serializeImage(content);
    content._cache[cacheKey] = serialized;
  }
  serialized = content._cache[cacheKey];
  if (serialized.externalUrl) {
    return {
      type: "image_url",
      image_url: {
        url: serialized.externalUrl,
        detail: serialized.inferenceDetail
      }
    };
  }
  if (serialized.base64Data === void 0) {
    throw new Error("Serialized image has no data bytes");
  }
  return {
    type: "image_url",
    image_url: {
      url: `data:${serialized.mimeType};base64,${serialized.base64Data}`,
      detail: serialized.inferenceDetail
    }
  };
}
async function toResponsesImageContent(content) {
  const cacheKey = "serialized_image";
  let serialized;
  if (content._cache[cacheKey] === void 0) {
    serialized = await serializeImage(content);
    content._cache[cacheKey] = serialized;
  }
  serialized = content._cache[cacheKey];
  if (serialized.externalUrl) {
    return {
      type: "input_image",
      image_url: serialized.externalUrl,
      detail: serialized.inferenceDetail
    };
  }
  if (serialized.base64Data === void 0) {
    throw new Error("Serialized image has no data bytes");
  }
  return {
    type: "input_image",
    image_url: `data:${serialized.mimeType};base64,${serialized.base64Data}`,
    detail: serialized.inferenceDetail
  };
}
async function toResponsesChatCtx(chatCtx, injectDummyUserMessage = true) {
  const itemGroups = groupToolCalls(chatCtx);
  const messages = [];
  for (const group of itemGroups) {
    if (group.isEmpty) continue;
    if (group.message) {
      messages.push(await toResponsesChatItem(group.message));
    }
    for (const toolCall of group.toolCalls) {
      messages.push({
        type: "function_call",
        call_id: toolCall.callId,
        name: toolCall.name,
        arguments: toolCall.args
      });
    }
    for (const toolOutput of group.toolOutputs) {
      messages.push(await toResponsesChatItem(toolOutput));
    }
  }
  return messages;
}
async function toResponsesChatItem(item) {
  var _a, _b;
  if (item.type === "message") {
    const listContent = [];
    let textContent = "";
    for (const content2 of item.content) {
      if (typeof content2 === "string") {
        if (textContent) textContent += "\n";
        textContent += content2;
      } else if (isInstructions(content2)) {
        if (textContent) textContent += "\n";
        textContent += content2.value;
      } else if (content2.type === "image_content") {
        listContent.push(await toResponsesImageContent(content2));
      } else {
        throw new Error(`Unsupported content type: ${content2.type}`);
      }
    }
    const content = listContent.length == 0 ? textContent : textContent.length == 0 ? listContent : [...listContent, { type: "input_text", text: textContent }];
    const result = { role: item.role, content };
    if (item.role === "assistant") {
      const phase = (_b = (_a = item.extra) == null ? void 0 : _a.openai) == null ? void 0 : _b.phase;
      if (phase !== void 0) {
        result.phase = phase;
      }
    }
    return result;
  } else if (item.type === "function_call") {
    return {
      type: "function_call",
      call_id: item.callId,
      name: item.name,
      arguments: item.args
    };
  } else if (item.type === "function_call_output") {
    return {
      type: "function_call_output",
      call_id: item.callId,
      output: item.output
    };
  }
  throw new Error(`Unsupported item type: ${item["type"]}`);
}
export {
  toChatCtx,
  toResponsesChatCtx
};
//# sourceMappingURL=openai.js.map