import{AiSearchConversationRole as o,AiSearchError as i}from"@redocly/theme/core/constants";import{SSE_EVENTS as s,MAX_DISPLAYED_RESOURCES as a}from"../../constants";function l(e,n){if(e.length===0)return e;const t=e[e.length-1];return t.role===o.ASSISTANT&&!t.messageId?[...e.slice(0,-1),{...t,messageId:n}]:e}function S(e,n){if(e.length===0)return e;const t=e.findIndex(u=>u.id===n.toolCallId);if(t===-1)return e;const r=[...e];return r[t]={...r[t],result:n},r}function d(e,n){return e.type!==s.MESSAGE_ID?{}:(n.setConversation(t=>l(t,e.messageId)),{messageId:e.messageId})}function f(e,n){if(e.type!==s.SOURCES)return{};const t=e.sources.slice(0,a).map(({url:r,title:u})=>({url:r,title:u}));return n.setState(r=>r.status==="loading"?{...r,resources:t}:r),{resources:t}}function c(e,n){if(e.type!==s.ANSWER)return{};const t=n.accumulatedResponse+e.answer;return n.setState(r=>r.status==="loading"?{...r,response:t}:r),{accumulatedResponse:t}}function E(e,n){return e.type!==s.TOOL_CALL?{}:(n.setToolCalls(t=>[...t,{...e.toolCall,position:n.accumulatedResponse.length}]),{})}function R(e,n){return e.type!==s.TOOL_RESULT?{}:(n.setToolCalls(t=>S(t,e.result)),{})}function A(e,n){return e.type!==s.ERROR?{}:(n.setState(t=>t.status==="loading"?{status:"error",question:t.question,error:i.ErrorProcessingResponse}:t),{})}const h={[s.MESSAGE_ID]:d,[s.SOURCES]:f,[s.ANSWER]:c,[s.TOOL_CALL]:E,[s.TOOL_RESULT]:R,[s.ERROR]:A};function T(e,n){const t=h[e.type];return t?t(e,n):{}}export{T as handleSSEMessage};
