import{useCallback as w,useState as o}from"react";import{AiSearchError as c}from"@redocly/theme/core/constants";import{withPathPrefix as K}from"@redocly/theme/core/utils";import{ServerRoutes as L}from"../../../constants/common";import{useI18nConfig as U,useCurrentProduct as _,usePageVersions as j}from"../hooks";import{telemetry as B}from"../telemetry/index.js";function se(k,x){const[E,m]=o(),[p,g]=o([]),[M,P]=o(""),[O,l]=o([]),[Q,n]=o(!1),[v,e]=o(null),[I,i]=o(null),{currentLocale:F}=U(),J=_(),{versions:N=[]}=j()||{},h=N.find(t=>t?.active),R=w(()=>{m(""),g([]),n(!1),e(null)},[m,g,e]),G=w(()=>{R(),l([])},[R,l]);return{askQuestion:async(t,H)=>{if(!t)return;I&&I.abort();const A=new AbortController;i(A),R(),n(!0),P(t);let u="";fetch(K(L.ASK_AI),{method:"POST",body:JSON.stringify({text:t,history:H||[],locale:F,product:J?.name,filter:k?.filter,version:h&&{folder:h.folderId,label:h.label}}),signal:A.signal}).then(r=>{if(!r.ok){n(!1),r.status===401?e(c.Unauthorized):r.status===403?e(c.Forbidden):e(c.HttpRequestFailed);return}let f="";const y=r.body;if(!y)return;const T=y.getReader(),C=()=>{T.read().then(({value:d,done:V})=>{if(V){n(!1),i(null),f||e(c.EmptyResponse),t.trim().length>0&&u&&B.sendSearchAIQueryMessage({question:t,answer:f,resources:JSON.stringify(p),searchSessionId:x,messageId:u});return}const z=new TextDecoder().decode(d),D=/data: (.*)/g;let S;for(;(S=D.exec(z))!==null;){if(!S[1])continue;const a=JSON.parse(S[1]);if(a.messageId)u=a.messageId,l(s=>{if(s.length===0)return s;const b=s[s.length-1];return b.role==="assistant"&&!b.messageId?[...s.slice(0,-1),{...b,messageId:u}]:s});else if(a.answer)f+=a.answer,m(f);else if(a.sources){const s=Math.floor(Math.random()*3)+4;g(a.sources.slice(0,s))}}C()}).catch(d=>{d.name!=="AbortError"&&(console.error(d),n(!1),i(null),e(c.ErrorProcessingResponse))})};C()}).catch(r=>{r.name!=="AbortError"&&(console.error(r),n(!1),i(null),e(c.HttpRequestFailed))})},isGeneratingResponse:Q,response:E,resources:p,question:M,error:v,clearConversation:G,conversation:O,setConversation:l}}export{se as useAiSearch};
