import{Agent}from"./agent.js";import{AgentError,AgentErrorCode}from"./agent-call.js";async function checkXBindSupport(t){try{const e=await fetch(t,{method:"OPTIONS",headers:{"X-Capability-Check":"xbind"}});return"true"===e.headers.get("X-xBind-Support")?{supported:!0,endpoint:e.headers.get("X-xBind-Endpoint")||void 0,peerDID:e.headers.get("X-xBind-DID")||void 0,version:e.headers.get("X-xBind-Version")||void 0}:{supported:!1}}catch{return{supported:!1}}}async function sendViaXBind(t,e,r,o){const n=Date.now();if(!e.peerDID)throw new AgentError(AgentErrorCode.NETWORK_ERROR,"Server supports xBind but did not provide X-xBind-DID header",{url:t,capability:e});const i=e.peerDID,a=e.endpoint||t,s=new Uint8Array(16);crypto.getRandomValues(s);const d=Array.from(s).map(t=>t.toString(16).padStart(2,"0")).join(""),c=`xfetch_${Date.now()}_${d}`,p={correlationId:c,method:r.method||"GET",url:t,headers:r.headers||{},body:r.body?"string"==typeof r.body?r.body:JSON.stringify(r.body):void 0};return new Promise((e,s)=>{const d=setTimeout(()=>{s(new AgentError(AgentErrorCode.TIMEOUT,"xBind request timed out waiting for response",{url:t,correlationId:c,timeout:r.timeout||3e4}))},r.timeout||3e4);(async()=>{try{const u=await o.send({to:i,payload:p,scope:"xfetch",action:"http_request"});if(!u.ok)return clearTimeout(d),void s(new AgentError(AgentErrorCode.NETWORK_ERROR,`Failed to send xBind request: ${u.error}`,{url:t,error:u.error}));const l=`${a}/response/${c}`,g=100,h=(r.timeout||3e4)/g;for(let t=0;t<h;t++){await new Promise(t=>setTimeout(t,g));try{const t=await fetch(l);if(200===t.status){clearTimeout(d);const r=Date.now()-n;return void e(Object.assign(t,{usedXBind:!0,transport:{protocol:"xbind",latency:r,peerDID:i}}))}}catch{continue}}clearTimeout(d),s(new AgentError(AgentErrorCode.TIMEOUT,"Response not available after polling",{url:t,correlationId:c,polls:h}))}catch(e){clearTimeout(d),s(e instanceof AgentError?e:new AgentError(AgentErrorCode.NETWORK_ERROR,"xBind request failed",{url:t,error:String(e)}))}})()})}async function sendViaHTTP(t,e){const r=Date.now(),{forceXBind:o,disableXBind:n,agent:i,retry:a,...s}=e,d=await fetch(t,s),c=Date.now()-r;return Object.assign(d,{usedXBind:!1,transport:{protocol:t.startsWith("https")?"https":"http",latency:c}})}async function withRetry(t,e){const r=e?.maxAttempts??3,o=e?.initialDelay??1e3,n=e?.multiplier??2;let i,a=o;for(let e=1;e<=r;e++)try{return await t()}catch(t){if(i=t instanceof Error?t:new Error(String(t)),t instanceof Response&&t.status>=400&&t.status<500)throw t;e<r&&(await new Promise(t=>setTimeout(t,a)),a*=n)}throw i}export async function xfetch(t,e={}){let r;try{r=new URL(t)}catch(e){throw new AgentError(AgentErrorCode.INVALID_PARAMS,`Invalid URL: ${t}`,{url:t,error:e})}if(!["http:","https:"].includes(r.protocol))throw new AgentError(AgentErrorCode.INVALID_PARAMS,`Unsupported protocol: ${r.protocol}`,{url:t,protocol:r.protocol});const o=e.timeout??3e4,n=new AbortController,i=setTimeout(()=>n.abort(),o);try{const r=e.signal?AbortSignal.any?.([e.signal,n.signal])??n.signal:n.signal,o={...e,signal:r};if(e.disableXBind)return await withRetry(()=>sendViaHTTP(t,o),e.retry);const i=await checkXBindSupport(t);if(e.forceXBind&&!i.supported)throw new AgentError(AgentErrorCode.NETWORK_ERROR,`xBind required but endpoint does not support it: ${t}`,{url:t,forceXBind:!0,capability:i});if(i.supported){const r=e.agent??await Agent.from({identity:"ephemeral",identityTTL:36e5});return await withRetry(()=>sendViaXBind(t,i,o,r),e.retry)}return await withRetry(()=>sendViaHTTP(t,o),e.retry)}finally{clearTimeout(i)}}export async function isXBindSupported(t){return(await checkXBindSupport(t)).supported}export async function getXBindCapability(t){return checkXBindSupport(t)}