import {
  RenderAgentStateMessage
} from "./chunk-UWWMAJ7R.mjs";
import {
  RenderResultMessage
} from "./chunk-WEYDZBT7.mjs";
import {
  RenderTextMessage
} from "./chunk-OFYI4UU4.mjs";
import {
  UserMessage
} from "./chunk-HEIDCT7I.mjs";
import {
  AssistantMessage
} from "./chunk-3VNMQWGT.mjs";
import {
  RenderActionExecutionMessage
} from "./chunk-XB6QCUPB.mjs";
import {
  Suggestion,
  reloadSuggestions
} from "./chunk-WGAZXTUA.mjs";
import {
  CopilotDevConsole
} from "./chunk-22K5DDPF.mjs";
import {
  Input
} from "./chunk-QXTRFMPM.mjs";
import {
  Messages
} from "./chunk-6FTRYYR5.mjs";
import {
  ResponseButton
} from "./chunk-3XAXY2Z3.mjs";
import {
  ChatContext,
  ChatContextProvider
} from "./chunk-CBBFRI3Q.mjs";
import {
  __async,
  __spreadProps,
  __spreadValues
} from "./chunk-MRXNTQOX.mjs";

// src/components/chat/Chat.tsx
import React, { useEffect, useRef, useState } from "react";
import {
  useCopilotChat,
  useCopilotContext,
  useCopilotMessagesContext
} from "@copilotkit/react-core";
import { Role, TextMessage } from "@copilotkit/runtime-client-gql";
import { randomId } from "@copilotkit/shared";
import { runAgent, stopAgent } from "@copilotkit/react-core";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
function CopilotChat({
  instructions,
  onSubmitMessage,
  makeSystemMessage,
  showResponseButton = true,
  onInProgress,
  onStopGeneration,
  onReloadMessages,
  Messages: Messages2 = Messages,
  RenderTextMessage: RenderTextMessage2 = RenderTextMessage,
  RenderActionExecutionMessage: RenderActionExecutionMessage2 = RenderActionExecutionMessage,
  RenderAgentStateMessage: RenderAgentStateMessage2 = RenderAgentStateMessage,
  RenderResultMessage: RenderResultMessage2 = RenderResultMessage,
  Input: Input2 = Input,
  ResponseButton: ResponseButton2 = ResponseButton,
  className,
  icons,
  labels,
  AssistantMessage: AssistantMessage2 = AssistantMessage,
  UserMessage: UserMessage2 = UserMessage
}) {
  const { additionalInstructions, setChatInstructions } = useCopilotContext();
  useEffect(() => {
    if (!(additionalInstructions == null ? void 0 : additionalInstructions.length)) {
      setChatInstructions(instructions || "");
      return;
    }
    const combinedAdditionalInstructions = [
      instructions,
      "Additionally, follow these instructions:",
      ...additionalInstructions.map((instruction) => `- ${instruction}`)
    ];
    console.log("combinedAdditionalInstructions", combinedAdditionalInstructions);
    setChatInstructions(combinedAdditionalInstructions.join("\n") || "");
  }, [instructions, additionalInstructions]);
  const {
    visibleMessages,
    isLoading,
    currentSuggestions,
    sendMessage,
    stopGeneration,
    reloadMessages
  } = useCopilotChatLogic(
    makeSystemMessage,
    onInProgress,
    onSubmitMessage,
    onStopGeneration,
    onReloadMessages
  );
  const chatContext = React.useContext(ChatContext);
  const isVisible = chatContext ? chatContext.open : true;
  return /* @__PURE__ */ jsxs(WrappedCopilotChat, { icons, labels, className, children: [
    /* @__PURE__ */ jsx(CopilotDevConsole, {}),
    /* @__PURE__ */ jsxs(
      Messages2,
      {
        AssistantMessage: AssistantMessage2,
        UserMessage: UserMessage2,
        RenderTextMessage: RenderTextMessage2,
        RenderActionExecutionMessage: RenderActionExecutionMessage2,
        RenderAgentStateMessage: RenderAgentStateMessage2,
        RenderResultMessage: RenderResultMessage2,
        messages: visibleMessages,
        inProgress: isLoading,
        children: [
          currentSuggestions.length > 0 && /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("h6", { children: "Suggested:" }),
            /* @__PURE__ */ jsx("div", { className: "suggestions", children: currentSuggestions.map((suggestion, index) => /* @__PURE__ */ jsx(
              Suggestion,
              {
                title: suggestion.title,
                message: suggestion.message,
                partial: suggestion.partial,
                className: suggestion.className,
                onClick: (message) => sendMessage(message)
              },
              index
            )) })
          ] }),
          showResponseButton && visibleMessages.length > 0 && /* @__PURE__ */ jsx(
            ResponseButton2,
            {
              onClick: isLoading ? stopGeneration : reloadMessages,
              inProgress: isLoading
            }
          )
        ]
      }
    ),
    /* @__PURE__ */ jsx(Input2, { inProgress: isLoading, onSend: sendMessage, isVisible })
  ] });
}
function WrappedCopilotChat({
  children,
  icons,
  labels,
  className
}) {
  const chatContext = React.useContext(ChatContext);
  if (!chatContext) {
    return /* @__PURE__ */ jsx(ChatContextProvider, { icons, labels, open: true, setOpen: () => {
    }, children: /* @__PURE__ */ jsx("div", { className: `copilotKitChat ${className}`, children }) });
  }
  return /* @__PURE__ */ jsx(Fragment, { children });
}
var SUGGESTIONS_DEBOUNCE_TIMEOUT = 1e3;
var useCopilotChatLogic = (makeSystemMessage, onInProgress, onSubmitMessage, onStopGeneration, onReloadMessages) => {
  var _a;
  const {
    visibleMessages,
    appendMessage,
    reloadMessages: defaultReloadMessages,
    stopGeneration: defaultStopGeneration,
    runChatCompletion,
    isLoading
  } = useCopilotChat({
    id: randomId(),
    makeSystemMessage
  });
  const [currentSuggestions, setCurrentSuggestions] = useState([]);
  const suggestionsAbortControllerRef = useRef(null);
  const debounceTimerRef = useRef();
  const abortSuggestions = () => {
    var _a2;
    (_a2 = suggestionsAbortControllerRef.current) == null ? void 0 : _a2.abort();
    suggestionsAbortControllerRef.current = null;
  };
  const generalContext = useCopilotContext();
  const messagesContext = useCopilotMessagesContext();
  const context = __spreadValues(__spreadValues({}, generalContext), messagesContext);
  useEffect(() => {
    onInProgress == null ? void 0 : onInProgress(isLoading);
    abortSuggestions();
    debounceTimerRef.current = setTimeout(
      () => {
        if (!isLoading && Object.keys(context.chatSuggestionConfiguration).length !== 0) {
          suggestionsAbortControllerRef.current = new AbortController();
          reloadSuggestions(
            context,
            context.chatSuggestionConfiguration,
            setCurrentSuggestions,
            suggestionsAbortControllerRef
          );
        }
      },
      currentSuggestions.length == 0 ? 0 : SUGGESTIONS_DEBOUNCE_TIMEOUT
    );
    return () => {
      clearTimeout(debounceTimerRef.current);
    };
  }, [
    isLoading,
    context.chatSuggestionConfiguration,
    // hackish way to trigger suggestions reload on reset, but better than moving suggestions to the
    // global context
    visibleMessages.length == 0
  ]);
  const sendMessage = (messageContent) => __async(void 0, null, function* () {
    abortSuggestions();
    setCurrentSuggestions([]);
    const message = new TextMessage({
      content: messageContent,
      role: Role.User
    });
    if (onSubmitMessage) {
      try {
        yield onSubmitMessage(messageContent);
      } catch (error) {
        console.error("Error in onSubmitMessage:", error);
      }
    }
    appendMessage(message);
    return message;
  });
  const messages = visibleMessages;
  const { setMessages } = messagesContext;
  const currentAgentName = (_a = generalContext.agentSession) == null ? void 0 : _a.agentName;
  const restartCurrentAgent = (hint) => __async(void 0, null, function* () {
    if (generalContext.agentSession) {
      generalContext.setAgentSession(__spreadProps(__spreadValues({}, generalContext.agentSession), {
        nodeName: void 0,
        threadId: void 0
      }));
      generalContext.setCoagentStates((prevAgentStates) => {
        return __spreadProps(__spreadValues({}, prevAgentStates), {
          [generalContext.agentSession.agentName]: __spreadProps(__spreadValues({}, prevAgentStates[generalContext.agentSession.agentName]), {
            threadId: void 0,
            nodeName: void 0,
            runId: void 0
          })
        });
      });
    }
  });
  const runCurrentAgent = (hint) => __async(void 0, null, function* () {
    if (generalContext.agentSession) {
      yield runAgent(
        generalContext.agentSession.agentName,
        context,
        appendMessage,
        runChatCompletion,
        hint
      );
    }
  });
  const stopCurrentAgent = () => {
    if (generalContext.agentSession) {
      stopAgent(generalContext.agentSession.agentName, context);
    }
  };
  const setCurrentAgentState = (state) => {
    if (generalContext.agentSession) {
      generalContext.setCoagentStates((prevAgentStates) => {
        return __spreadProps(__spreadValues({}, prevAgentStates), {
          [generalContext.agentSession.agentName]: {
            state
          }
        });
      });
    }
  };
  function stopGeneration() {
    if (onStopGeneration) {
      onStopGeneration({
        messages,
        setMessages,
        stopGeneration: defaultStopGeneration,
        currentAgentName,
        restartCurrentAgent,
        stopCurrentAgent,
        runCurrentAgent,
        setCurrentAgentState
      });
    } else {
      defaultStopGeneration();
    }
  }
  function reloadMessages() {
    if (onReloadMessages) {
      onReloadMessages({
        messages,
        setMessages,
        stopGeneration: defaultStopGeneration,
        currentAgentName,
        restartCurrentAgent,
        stopCurrentAgent,
        runCurrentAgent,
        setCurrentAgentState
      });
    } else {
      defaultReloadMessages();
    }
  }
  return {
    visibleMessages,
    isLoading,
    currentSuggestions,
    sendMessage,
    stopGeneration,
    reloadMessages
  };
};

export {
  CopilotChat,
  WrappedCopilotChat,
  useCopilotChatLogic
};
//# sourceMappingURL=chunk-2C3ANQCY.mjs.map