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