import { generateId as xt } from "../../../../../@ai-sdk_provider-utils@2.2.8_zod@3.24.4/node_modules/@ai-sdk/provider-utils/dist/index.js";
import { fillMessageParts as J, extractMaxToolInvocationStep as St, callChatApi as At, shouldResubmitMessages as _t, prepareAttachmentsForRequest as rt, getMessageParts as wt, updateToolCallResult as Rt, isAssistantMessageWithCompletedToolCalls as It, isDeepEqualData as Tt } from "../../../../../@ai-sdk_ui-utils@1.2.11_zod@3.24.4/node_modules/@ai-sdk/ui-utils/dist/index.js";
import { useState as L, useMemo as Ft, useRef as T, useEffect as P, useCallback as u } from "react";
import F from "../../../../../swr@2.3.3_react@18.3.0-canary-3d9b20132-20240124/node_modules/swr/dist/index/index.js";
import Pt from "../../../../../../../_virtual/index4.js";
function ot(r, c) {
  return c != null ? Pt(r, c) : r;
}
function kt(r) {
  const [c, A] = L(r);
  return P(() => {
    Tt(r, c) || A(r);
  }, [r, c]), c;
}
function jt({
  api: r = "/api/chat",
  id: c,
  initialMessages: A,
  initialInput: lt = "",
  sendExtraMessageFields: N,
  onToolCall: O,
  experimental_prepareRequestBody: k,
  maxSteps: Q = 1,
  streamProtocol: X = "data",
  onResponse: Y,
  onFinish: Z,
  onError: E,
  credentials: q,
  headers: K,
  body: U,
  generateId: d = xt,
  fetch: $,
  keepLastMessageOnError: B = !0,
  experimental_throttle: W
} = {}) {
  const [ct] = L(d), f = c ?? ct, _ = typeof r == "string" ? [r, f] : f, V = kt(A ?? []), ut = Ft(
    () => J(V),
    [V]
  ), { data: v, mutate: h } = F(
    [_, "messages"],
    null,
    { fallbackData: ut }
  ), o = T(v || []);
  P(() => {
    o.current = v || [];
  }, [v]);
  const { data: w, mutate: R } = F([_, "streamData"], null), M = T(w);
  P(() => {
    M.current = w;
  }, [w]);
  const { data: b = "ready", mutate: y } = F([_, "status"], null), { data: it = void 0, mutate: j } = F([_, "error"], null), i = T(null), g = T({
    credentials: q,
    headers: K,
    body: U
  });
  P(() => {
    g.current = {
      credentials: q,
      headers: K,
      body: U
    };
  }, [q, K, U]);
  const l = u(
    async (t, a = "generate") => {
      var s, n;
      y("submitted"), j(void 0);
      const e = J(t.messages), C = e.length, p = St(
        (s = e[e.length - 1]) == null ? void 0 : s.toolInvocations
      );
      try {
        const m = new AbortController();
        i.current = m;
        const G = ot(h, W), Mt = ot(
          R,
          W
        ), Dt = o.current;
        G(e, !1);
        const Ct = N ? e : e.map(
          ({
            role: H,
            content: S,
            experimental_attachments: I,
            data: et,
            annotations: st,
            toolInvocations: at,
            parts: nt
          }) => ({
            role: H,
            content: S,
            ...I !== void 0 && {
              experimental_attachments: I
            },
            ...et !== void 0 && { data: et },
            ...st !== void 0 && { annotations: st },
            ...at !== void 0 && { toolInvocations: at },
            ...nt !== void 0 && { parts: nt }
          })
        ), tt = M.current;
        await At({
          api: r,
          body: (n = k?.({
            id: f,
            messages: e,
            requestData: t.data,
            requestBody: t.body
          })) != null ? n : {
            id: f,
            messages: Ct,
            data: t.data,
            ...g.current.body,
            ...t.body
          },
          streamProtocol: X,
          credentials: g.current.credentials,
          headers: {
            ...g.current.headers,
            ...t.headers
          },
          abortController: () => i.current,
          restoreMessagesOnFailure() {
            B || G(Dt, !1);
          },
          onResponse: Y,
          onUpdate({ message: H, data: S, replaceLastMessage: I }) {
            y("streaming"), G(
              [
                ...I ? e.slice(0, e.length - 1) : e,
                H
              ],
              !1
            ), S?.length && Mt(
              [...tt ?? [], ...S],
              !1
            );
          },
          onToolCall: O,
          onFinish: Z,
          generateId: d,
          fetch: $,
          lastMessage: e[e.length - 1],
          requestType: a
        }), i.current = null, y("ready");
      } catch (m) {
        if (m.name === "AbortError")
          return i.current = null, y("ready"), null;
        E && m instanceof Error && E(m), j(m), y("error");
      }
      const x = o.current;
      _t({
        originalMaxToolInvocationStep: p,
        originalMessageCount: C,
        maxSteps: Q,
        messages: x
      }) && await l({ messages: x });
    },
    [
      h,
      y,
      r,
      g,
      Y,
      Z,
      E,
      j,
      R,
      M,
      X,
      N,
      k,
      O,
      Q,
      o,
      i,
      d,
      $,
      B,
      W,
      f
    ]
  ), mt = u(
    async (t, {
      data: a,
      headers: s,
      body: n,
      experimental_attachments: e = t.experimental_attachments
    } = {}) => {
      var C, p;
      const x = await rt(
        e
      ), m = o.current.concat({
        ...t,
        id: (C = t.id) != null ? C : d(),
        createdAt: (p = t.createdAt) != null ? p : /* @__PURE__ */ new Date(),
        experimental_attachments: x.length > 0 ? x : void 0,
        parts: wt(t)
      });
      return l({ messages: m, headers: s, body: n, data: a });
    },
    [l, d]
  ), dt = u(
    async ({ data: t, headers: a, body: s } = {}) => {
      const n = o.current;
      if (n.length === 0)
        return null;
      const e = n[n.length - 1];
      return l({
        messages: e.role === "assistant" ? n.slice(0, -1) : n,
        headers: a,
        body: s,
        data: t
      });
    },
    [l]
  ), gt = u(() => {
    i.current && (i.current.abort(), i.current = null);
  }, []), ft = u(async () => {
    const t = o.current;
    l({ messages: t }, "resume");
  }, [l]), ht = u(
    (t) => {
      typeof t == "function" && (t = t(o.current));
      const a = J(t);
      h(a, !1), o.current = a;
    },
    [h]
  ), bt = u(
    (t) => {
      typeof t == "function" && (t = t(M.current)), R(t, !1), M.current = t;
    },
    [R]
  ), [D, z] = L(lt), yt = u(
    async (t, a = {}, s) => {
      var n;
      if ((n = t?.preventDefault) == null || n.call(t), !D && !a.allowEmptySubmit)
        return;
      s && (g.current = {
        ...g.current,
        ...s
      });
      const e = await rt(
        a.experimental_attachments
      ), p = {
        messages: o.current.concat({
          id: d(),
          createdAt: /* @__PURE__ */ new Date(),
          role: "user",
          content: D,
          experimental_attachments: e.length > 0 ? e : void 0,
          parts: [{ type: "text", text: D }]
        }),
        headers: a.headers,
        body: a.body,
        data: a.data
      };
      l(p), z("");
    },
    [D, d, l]
  ), pt = (t) => {
    z(t.target.value);
  }, vt = u(
    ({ toolCallId: t, result: a }) => {
      const s = o.current;
      if (Rt({
        messages: s,
        toolCallId: t,
        toolResult: a
      }), h(
        [
          ...s.slice(0, s.length - 1),
          { ...s[s.length - 1] }
        ],
        !1
      ), b === "submitted" || b === "streaming")
        return;
      const n = s[s.length - 1];
      It(n) && l({ messages: s });
    },
    [h, b, l]
  );
  return {
    messages: v ?? [],
    id: f,
    setMessages: ht,
    data: w,
    setData: bt,
    error: it,
    append: mt,
    reload: dt,
    stop: gt,
    experimental_resume: ft,
    input: D,
    setInput: z,
    handleInputChange: pt,
    handleSubmit: yt,
    isLoading: b === "submitted" || b === "streaming",
    status: b,
    addToolResult: vt
  };
}
export {
  jt as useChat
};
//# sourceMappingURL=index.js.map
