import{useCallback as E,useEffect as Q,useMemo as J,useRef as m,useState as y}from"react";import{AiSearchError as d}from"@redocly/theme/core/constants";import{withPathPrefix as N,splitContentByToolCalls as V}from"@redocly/theme/core/utils";import{ServerRoutes as j}from"../../../constants/api";import{useSearchSession as B}from"@redocly/theme/core/contexts";import{AI_SEARCH_REQUEST_HEADERS as D,HTTP_ERROR_MAP as G}from"../../constants";import{useI18nConfig as K,usePageVersions as L}from"../hooks";import{telemetry as U}from"../telemetry/index.js";import{streamSSEMessages as $}from"./sse-parser";import{handleSSEMessage as z}from"./message-handlers";function or(u){const{searchSessionId:p}=B(),[r,t]=y({status:"idle"}),[P,g]=y([]),[S,b]=y([]),o=m(null),a=m(""),n=m(""),i=m([]),{currentLocale:C}=K(),{versions:_=[]}=L()||{},l=_.find(e=>e?.active),f=E(()=>{t({status:"idle",response:""}),b([]),a.current="",n.current="",i.current=[]},[]),w=E(()=>{o.current?.abort(),o.current=null,f(),g([])},[f]);Q(()=>()=>{o.current?.abort()},[]);const O=E(async(e,q)=>{if(!e)return;o.current?.abort();const h=new AbortController;o.current=h,f(),t({status:"loading",question:e,response:"",resources:[]});try{const c=await fetch(N(j.ASK_AI),{method:"POST",headers:D,body:JSON.stringify({text:e,history:q||[],locale:C,product:u?.product,filter:u?.filter,version:l&&{folder:l.folderId,label:l.label},searchSessionId:p}),signal:h.signal});if(!c.ok){t({status:"error",question:e,error:G[c.status]??d.HttpRequestFailed});return}const A=c.body;if(!A){t({status:"error",question:e,error:d.HttpRequestFailed});return}let I=!1;for await(const s of $(A,h.signal)){const F={messageId:a.current,resources:i.current,accumulatedResponse:n.current,setConversation:g,setState:t,setToolCalls:b},{messageId:v,resources:H,accumulatedResponse:M}=z(s,F);v&&(a.current=v),H&&(i.current=H),M&&(n.current=M),s.type==="error"&&(I=!0)}if(o.current=null,t(s=>s.status==="error"?s:n.current?{status:"success",question:e,response:n.current,resources:i.current}:{status:"error",question:e,error:d.EmptyResponse}),!I&&n.current&&e.trim()&&a.current){const s=a.current;U.sendSearchAIQueryMessage([{id:s,object:"aiSearchMessage",uri:`urn:redocly:realm:ui:aiSearchMessage:${s}`,question:e,answer:n.current,resources:JSON.stringify(i.current),searchSessionId:p,messageId:s,source:"realm",...u?.product&&{product:u.product}}])}}catch(c){if(c instanceof Error&&c.name==="AbortError")return;o.current=null,t({status:"error",question:e,error:d.HttpRequestFailed})}},[f,u?.product,C,u?.filter,l,p]),R=r.status==="loading"||r.status==="success"||r.status==="idle"?r.response:void 0,k=J(()=>V(R,S),[R,S]);return{askQuestion:O,isGeneratingResponse:r.status==="loading",response:R,resources:r.status==="loading"||r.status==="success"?r.resources:[],question:r.status!=="idle"?r.question:"",error:r.status==="error"?r.error:null,clearConversation:w,conversation:P,setConversation:g,toolCalls:S,contentSegments:k}}export{or as useAiSearch};
