/**
 * This file is part of the NocoBase (R) project.
 * Copyright (c) 2020-2024 NocoBase Co., Ltd.
 * Authors: NocoBase Team.
 *
 * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
 * For more information, please refer to: https://www.nocobase.com/agreement.
 */

var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var parse_messages_exports = {};
__export(parse_messages_exports, {
  parseMessages: () => parseMessages
});
module.exports = __toCommonJS(parse_messages_exports);
var import_messages = require("@langchain/core/messages");
var import_path = __toESM(require("path"));
var import_fs = __toESM(require("fs"));
var import_axios = __toESM(require("axios"));
async function encodeLocalImage(url) {
  url = import_path.default.join(process.cwd(), url);
  const imageData = await import_fs.default.promises.readFile(url);
  return `data:image/png;base64,${imageData.toString("base64")}`;
}
async function encodeImage(url) {
  if (!url.startsWith("http")) {
    return encodeLocalImage(url);
  }
  const response = await import_axios.default.get(url, { responseType: "arraybuffer" });
  return `data:image/png;base64,${Buffer.from(response.data).toString("base64")}`;
}
async function parseMessage(message) {
  switch (message.role) {
    case "system":
      return new import_messages.SystemMessage(message.message);
    case "assistant":
      return new import_messages.AIMessage(message.message);
    case "user": {
      if (message.content.length === 1) {
        const msg = message.content[0];
        if (msg.type === "text") {
          return new import_messages.HumanMessage(msg.content);
        }
      }
      const content = [];
      for (const c of message.content) {
        if (c.type === "text") {
          content.push({
            type: "text",
            text: c.content
          });
        }
        if (c.type === "image_url") {
          let urls = c.image_url.url;
          if (!Array.isArray(urls)) {
            urls = [urls];
          }
          for (let url of urls) {
            if (typeof url !== "string") {
              url = url.url;
            }
            if (url && !url.startsWith("http")) {
              try {
                url = await encodeLocalImage(url);
              } catch (e) {
                throw new Error(`Failed to encode image ${url}: ${e.message}`);
              }
            }
            if (!url) {
              continue;
            }
            content.push({
              type: "image_url",
              image_url: { url }
            });
          }
        }
        if (c.type === "image_base64") {
          let urls = c.image_url.url;
          if (!Array.isArray(urls)) {
            urls = [urls];
          }
          for (let url of urls) {
            if (typeof url !== "string") {
              url = url.url;
            }
            try {
              url = await encodeImage(url);
            } catch (e) {
              throw new Error(`Failed to encode image ${url}: ${e.message}`);
            }
            if (!url) {
              continue;
            }
            content.push({
              type: "image_url",
              image_url: { url }
            });
          }
        }
      }
      return new import_messages.HumanMessage({
        content
      });
    }
  }
}
async function parseMessages(messages) {
  const msgs = [];
  for (const message of messages) {
    const msg = await parseMessage(message);
    msgs.push(msg);
  }
  return msgs;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  parseMessages
});
