// src/convert-to-sap-messages.ts
import {
  InvalidPromptError,
  UnsupportedFunctionalityError
} from "@ai-sdk/provider";
import { Buffer } from "buffer";
var ZERO_WIDTH_SPACE = "\u200B";
var JINJA2_DELIMITERS_PATTERN = /\{(?=[{%#])/g;
var JINJA2_DELIMITERS_ESCAPED_PATTERN = new RegExp(`\\{${ZERO_WIDTH_SPACE}([{%#])`, "g");
function convertToSAPMessages(prompt, options = {}) {
  const messages = [];
  const includeReasoning = options.includeReasoning ?? false;
  const escapeTemplatePlaceholders = options.escapeTemplatePlaceholders ?? true;
  const maybeEscape = (text) => escapeTemplatePlaceholders ? escapeOrchestrationPlaceholders(text) : text;
  for (const message of prompt) {
    switch (message.role) {
      case "assistant": {
        let text = "";
        const toolCalls = [];
        for (const part of message.content) {
          switch (part.type) {
            case "reasoning": {
              if (includeReasoning && part.text) {
                text += `<think>${maybeEscape(part.text)}</think>`;
              }
              break;
            }
            case "text": {
              text += maybeEscape(part.text);
              break;
            }
            case "tool-call": {
              let argumentsJson;
              if (typeof part.input === "string") {
                try {
                  JSON.parse(part.input);
                  argumentsJson = part.input;
                } catch {
                  argumentsJson = JSON.stringify(part.input);
                }
              } else {
                argumentsJson = JSON.stringify(part.input);
              }
              toolCalls.push({
                function: {
                  arguments: maybeEscape(argumentsJson),
                  name: part.toolName
                },
                id: part.toolCallId,
                type: "function"
              });
              break;
            }
          }
        }
        const assistantMessage = {
          content: text || "",
          role: "assistant",
          tool_calls: toolCalls.length > 0 ? toolCalls : void 0
        };
        messages.push(assistantMessage);
        break;
      }
      case "system": {
        const systemMessage = {
          content: maybeEscape(message.content),
          role: "system"
        };
        messages.push(systemMessage);
        break;
      }
      case "tool": {
        for (const part of message.content) {
          if (part.type === "tool-result") {
            const serializedOutput = JSON.stringify(part.output);
            const toolMessage = {
              content: maybeEscape(serializedOutput),
              role: "tool",
              tool_call_id: part.toolCallId
            };
            messages.push(toolMessage);
          }
        }
        break;
      }
      case "user": {
        const contentParts = [];
        for (const part of message.content) {
          switch (part.type) {
            case "file": {
              if (!part.mediaType.startsWith("image/")) {
                throw new UnsupportedFunctionalityError({
                  functionality: "Only image files are supported"
                });
              }
              const supportedFormats = [
                "image/png",
                "image/jpeg",
                "image/jpg",
                "image/gif",
                "image/webp"
              ];
              if (!supportedFormats.includes(part.mediaType.toLowerCase())) {
                console.warn(
                  `Image format ${part.mediaType} may not be supported by all models. Recommended formats: PNG, JPEG, GIF, WebP`
                );
              }
              let imageUrl;
              if (part.data instanceof URL) {
                imageUrl = part.data.toString();
              } else if (typeof part.data === "string") {
                imageUrl = `data:${part.mediaType};base64,${part.data}`;
              } else if (part.data instanceof Uint8Array) {
                const base64Data = Buffer.from(part.data).toString("base64");
                imageUrl = `data:${part.mediaType};base64,${base64Data}`;
              } else if (Buffer.isBuffer(part.data)) {
                const base64Data = Buffer.from(part.data).toString("base64");
                imageUrl = `data:${part.mediaType};base64,${base64Data}`;
              } else {
                const maybeBufferLike = part.data;
                if (maybeBufferLike !== null && typeof maybeBufferLike === "object" && "toString" in maybeBufferLike) {
                  const base64Data = maybeBufferLike.toString("base64");
                  imageUrl = `data:${part.mediaType};base64,${base64Data}`;
                } else {
                  throw new UnsupportedFunctionalityError({
                    functionality: "Unsupported file data type for image. Expected URL, base64 string, or Uint8Array."
                  });
                }
              }
              contentParts.push({
                image_url: {
                  url: imageUrl
                },
                type: "image_url"
              });
              break;
            }
            case "text": {
              contentParts.push({
                text: maybeEscape(part.text),
                type: "text"
              });
              break;
            }
            default: {
              throw new UnsupportedFunctionalityError({
                functionality: `Content type ${part.type}`
              });
            }
          }
        }
        const firstPart = contentParts[0];
        const userMessage = contentParts.length === 1 && firstPart?.type === "text" ? {
          content: firstPart.text ?? "",
          role: "user"
        } : {
          content: contentParts,
          role: "user"
        };
        messages.push(userMessage);
        break;
      }
      default: {
        const _exhaustiveCheck = message;
        throw new InvalidPromptError({
          message: `Unsupported role: ${_exhaustiveCheck.role}`,
          prompt: JSON.stringify(message)
        });
      }
    }
  }
  return messages;
}
function escapeOrchestrationPlaceholders(text) {
  if (!text) return text;
  return text.replaceAll(JINJA2_DELIMITERS_PATTERN, `{${ZERO_WIDTH_SPACE}`);
}
function unescapeOrchestrationPlaceholders(text) {
  if (!text) return text;
  return text.replaceAll(JINJA2_DELIMITERS_ESCAPED_PATTERN, "{$1");
}

export {
  convertToSAPMessages,
  escapeOrchestrationPlaceholders,
  unescapeOrchestrationPlaceholders
};
//# sourceMappingURL=chunk-G2BVB5LB.js.map