"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var do_prompt_stream_of_streams_exports = {};
__export(do_prompt_stream_of_streams_exports, {
  doPromptStreamOfStreams: () => doPromptStreamOfStreams
});
module.exports = __toCommonJS(do_prompt_stream_of_streams_exports);
const MAX_CONVERSATION_COLOR_PALETTE_SIZE = 6;
const toStreamError = (args) => {
  const message = args.message ?? args.applicationError?.description ?? args.statusFallback;
  return {
    type: "error",
    message,
    status: args.status,
    applicationErrorCode: args.applicationError?.code
  };
};
const doPromptStreamOfStreams = async function* ({
  prompt,
  document,
  selection,
  makeRequest,
  getCurrentTheme,
  invocationId,
  files,
  traceParams,
  systemPromptId,
  aiProjectId,
  useWixelWidgets
}) {
  try {
    const promptIdFromQuery = new URLSearchParams(window.location.search).get("ricosPromptId");
    const promptIdFromArg = systemPromptId && looksLikeUUID(systemPromptId) ? systemPromptId : void 0;
    const promptIdFromUrl = promptIdFromQuery && looksLikeUUID(promptIdFromQuery) ? promptIdFromQuery : void 0;
    const promptId = promptIdFromUrl ?? promptIdFromArg;
    const currentTheme = getCurrentTheme?.();
    const conversationTheme = currentTheme?.colorPalette?.length > MAX_CONVERSATION_COLOR_PALETTE_SIZE ? {
      ...currentTheme,
      colorPalette: currentTheme.colorPalette.slice(0, MAX_CONVERSATION_COLOR_PALETTE_SIZE)
    } : currentTheme;
    const baseUrl = typeof location !== "undefined" && location.hostname === "editor.wix.com" ? "https://editor.wix.com/_api/ricos-ai-assistant/v1/ricos-conversations" : "https://www.wixapis.com/ricos/v1/ricos-conversations";
    const conversationResponse = await makeRequest(`${baseUrl}/async`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
        // Accept: 'application/x-ndjson',
      },
      body: JSON.stringify({
        ricosConversation: {
          promptId,
          message: prompt,
          theme: conversationTheme ?? void 0,
          returnMetadata: true,
          document,
          documentSelection: { nodes: selection },
          files: files?.map((f) => ({
            fileName: f.fileName || void 0,
            mimeType: f.mimeType || void 0,
            ...f.fileUrl.includes("https://") ? { fileUrl: f.fileUrl } : { fileId: f.fileUrl }
          })) ?? void 0,
          traceParams,
          projectId: useWixelWidgets ? "776d2a7f-5bc4-4ba0-b414-74cf7599cf15" : aiProjectId || void 0
        },
        invocationId
      })
    }).catch((e) => ({ ok: false, status: -1, statusText: e.message }));
    if (!conversationResponse.ok) {
      const errorBody = await conversationResponse.json().catch(() => ({}));
      yield toStreamError({
        message: errorBody.message,
        applicationError: errorBody.details?.applicationError,
        status: conversationResponse.status,
        statusFallback: `Error: ${conversationResponse.status} ${conversationResponse.statusText}`
      });
      return;
    }
    const requestId = conversationResponse.headers.get("x-wix-request-id");
    console.log(
      "\x1B[44m\x1B[97m RICOS PROMPT  \x1B[0m",
      prompt,
      `invocationId=${invocationId}`,
      `requestId=${requestId ?? ""}`
    );
    const result = await conversationResponse.json();
    let cursor = "";
    let emptyRetries = 0;
    while (true) {
      const chunkResponse = await makeRequest(
        `${baseUrl}/${result.conversationId}${cursor ? `?cursor=${cursor}` : ""}`,
        {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
            Accept: "application/x-ndjson"
          }
        }
      ).catch((e) => ({ ok: false, status: -1, statusText: e.message }));
      const reader = chunkResponse.body?.getReader();
      if (!reader) {
        yield { type: "error", message: "Error: No chunk response body" };
        return;
      }
      let receivedAnyData = false;
      for await (const chunk of readJsonStream(reader)) {
        receivedAnyData = true;
        if ("chunk" in chunk) {
          cursor = "next" in chunk ? chunk.next : "";
          yield chunk;
          if (!cursor) {
            return;
          }
        }
        if ("status" in chunk) {
          const errorChunk = chunk;
          yield toStreamError({
            message: errorChunk.message,
            applicationError: errorChunk.details?.applicationError,
            status: errorChunk.status,
            statusFallback: `Error: ${errorChunk.status}`
          });
          return;
        }
      }
      if (!receivedAnyData) {
        emptyRetries++;
        if (emptyRetries > 1) {
          yield {
            type: "error",
            message: "Error: No chunks received from AI service",
            status: -1
          };
          return;
        }
      } else {
        emptyRetries = 0;
      }
    }
  } catch (e) {
    yield { type: "error", message: `Error: ${e.message}` };
  }
};
async function* readJsonStream(reader) {
  const decoder = new TextDecoder("utf-8");
  let buffer = "";
  try {
    while (true) {
      const { done, value } = await reader.read();
      if (done) {
        break;
      }
      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split("\n");
      buffer = lines.pop() ?? "";
      for (const line of lines) {
        if (line.trim()) {
          const json = JSON.parse(line);
          yield json;
        }
      }
    }
    if (buffer.trim()) {
      const json = JSON.parse(buffer);
      yield json;
    }
  } finally {
    reader.releaseLock();
  }
}
const looksLikeUUID = (str) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(str);
//# sourceMappingURL=do-prompt-stream-of-streams.js.map
