"use strict";
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 inline_ai_context_provider_exports = {};
__export(inline_ai_context_provider_exports, {
  InlineAiContextProvider: () => InlineAiContextProvider,
  computeStopTransition: () => computeStopTransition,
  useInlineAiState: () => useInlineAiState,
  useInlineAiStateWithSelectorContextValue: () => useInlineAiStateWithSelectorContextValue
});
module.exports = __toCommonJS(inline_ai_context_provider_exports);
var React = __toESM(require("react"));
var import_orchestrator_context = require("./../ricos-context/orchestrator-context.js");
var import_log_invariant = require("./../_shared/log-invariant.js");
var import_use_context_selector = require("./../_shared/use-context-selector.js");
var import_cursor_context = require("./cursor-context.js");
var import_execute_prompt = require("./execute-prompt.js");
var import_inline_ai_context = require("./inline-ai-context.js");
var import_keepable_partial_messages = require("./keepable-partial-messages.js");
var import_pager_api = require("./pager-api.js");
var import_types = require("./types.js");
const INITIAL_STATE = {
  invocations: {}
};
const InlineAiContextProvider = ({ children, plugins }) => {
  const [inlineAiState, setInlineAiState] = React.useState(INITIAL_STATE);
  const cursorAnchorRef = React.useRef(null);
  const [cursorState, setCursorStateRaw] = React.useState({
    showCursor: false,
    label: null
  });
  const setCursorState = React.useCallback((state) => setCursorStateRaw(state), []);
  const orchestrator = (0, import_orchestrator_context.useOrchestrator)();
  const inlineAiPluginConfig = plugins.getConfig(import_types.INLINE_AI_PLUGIN_TYPE);
  const value = [
    inlineAiState,
    setInlineAiState
  ];
  return /* @__PURE__ */ React.createElement(import_cursor_context.CursorContext.Provider, { value: { cursorAnchorRef, cursorState, setCursorState } }, /* @__PURE__ */ React.createElement(
    import_inline_ai_context.InlineAiContext.Provider,
    {
      value,
      onSelectorContextValue: (x) => {
        orchestrator.inlineAiStateSelectorContextValue = x;
      }
    },
    /* @__PURE__ */ React.createElement(
      SetupExecutePrompt,
      {
        orchestrator,
        aiProjectId: inlineAiPluginConfig.aiProjectId,
        useWixelWidgets: inlineAiPluginConfig.useWixelWidgets
      }
    ),
    children
  ));
};
const SetupExecutePrompt = ({ orchestrator, aiProjectId, useWixelWidgets }) => {
  const executePrompt = (0, import_execute_prompt.useExecutePrompt)(aiProjectId, useWixelWidgets);
  if (orchestrator.inlineAiService) {
    orchestrator.inlineAiService.executePrompt = executePrompt;
  } else {
    (0, import_log_invariant.logInvariant)(new Error("Inline AI service is not available"));
  }
  return null;
};
const computeStopTransition = (s, { headless, keepChanges }) => {
  if (s.type === "pending" || s.type === "streaming") {
    const prompt = s.prompt;
    const messages = "messages" in s ? s.messages : [];
    const chunks = "chunks" in s ? s.chunks : [];
    if (keepChanges && (0, import_keepable_partial_messages.hasKeepablePartialMessages)(messages)) {
      return { type: "closed", messages, chunks, prompt };
    }
    return headless ? {
      type: "error",
      error: { message: "Cancelled by user", applicationErrorCode: "USER_CANCELLED" },
      messages,
      chunks,
      prompt
    } : { type: "typing", value: prompt };
  }
  return s;
};
const useInlineAiStateWithSelectorContextValue = (selectorContextValue, invocationId, defaultValue) => {
  const [stateSlice, setState] = (0, import_use_context_selector.useContextSelectorWithValue)(
    selectorContextValue,
    (ctx) => [ctx?.[0]?.invocations?.[invocationId], ctx?.[1]],
    (a, b) => a[0] === b[0]
  );
  if (!setState) {
    throw new Error("useInlineAiApi must be used within an InlineAiContextProvider");
  }
  const setStateSlice = (newState) => setState((prevState) => {
    const currentInvocationState = prevState.invocations[invocationId] ?? defaultValue;
    const nextInvocationState = typeof newState === "function" ? newState(currentInvocationState) : newState;
    return {
      ...prevState,
      invocations: {
        ...prevState.invocations,
        [invocationId]: nextInvocationState
      }
    };
  });
  const state = stateSlice ?? defaultValue;
  const stop = ({ headless, keepChanges }) => {
    setStateSlice((s) => computeStopTransition(s, { headless, keepChanges }));
  };
  const triggerPreview = () => {
    setStateSlice((s) => {
      if (s.type !== "closed") {
        return s;
      }
      const actionableMessages = s.messages.filter(
        (m) => m.type === "insert" || m.type === "replace"
      );
      if (actionableMessages.length === 0) {
        return s;
      }
      return {
        type: "preview",
        messages: s.messages,
        activeMessageIndex: s.messages.findLastIndex((m) => m.type !== "text"),
        chunks: s.chunks,
        prompt: s.prompt
      };
    });
  };
  return {
    state,
    setState: setStateSlice,
    stop,
    triggerPreview,
    pagerAPI: state?.type !== "preview" ? void 0 : (0, import_pager_api.getPagerAPI)(
      state.messages,
      state.activeMessageIndex,
      (index) => {
        setStateSlice(
          (prev) => prev && prev.type === "preview" ? { ...prev, activeMessageIndex: index } : prev
        );
      },
      (arg) => {
        setStateSlice(
          (prev) => prev && prev.type === "preview" ? { ...prev, messages: typeof arg === "function" ? arg(prev.messages) : arg } : prev
        );
      }
    )
  };
};
const useInlineAiState = (invocationId, defaultValue) => {
  const context = React.useContext(
    import_inline_ai_context.InlineAiContext
  );
  if (!context) {
    throw new Error("useInlineAiApi must be used within an InlineAiContextProvider");
  }
  return useInlineAiStateWithSelectorContextValue(context, invocationId, defaultValue);
};
//# sourceMappingURL=inline-ai-context-provider.js.map
