import{ok,err}from"./_deps/shared/index.js";export var DualModeErrorCode;!function(a){a.BOTH_FAILED="DUAL_MODE_BOTH_FAILED",a.XBIND_FAILED="DUAL_MODE_XBIND_FAILED",a.FALLBACK_FAILED="DUAL_MODE_FALLBACK_FAILED",a.INVALID_CONFIG="DUAL_MODE_INVALID_CONFIG"}(DualModeErrorCode||(DualModeErrorCode={}));export class DualModeAdapter{xbind;fallback;metrics;constructor(a={}){this.xbind=a.xbind||null,this.fallback=a.fallback||null,this.metrics={totalCalls:0,xbindCalls:0,fallbackCalls:0,xbindPercentage:0,lastCall:(new Date).toISOString(),lastCallMethod:"xbind"}}setXBind(a){this.xbind=a}removeFallback(){this.fallback=null}async call(a,r={}){if(this.metrics.totalCalls++,this.xbind)try{const e=await this.callViaXBind(a,r);if(e.ok)return this.metrics.xbindCalls++,this.updateMetrics("xbind"),e;if(this.fallback){const t=await this.callViaFallback(a,r);return t.ok?(this.metrics.fallbackCalls++,this.updateMetrics("fallback"),t):err({code:DualModeErrorCode.BOTH_FAILED,message:"Both XBind and fallback failed",xbindError:e.error,fallbackError:t.error})}return err({code:DualModeErrorCode.XBIND_FAILED,message:"XBind failed and no fallback configured",xbindError:e.error})}catch(e){if(this.fallback){const e=await this.callViaFallback(a,r);if(e.ok)return this.metrics.fallbackCalls++,this.updateMetrics("fallback"),e}return err({code:DualModeErrorCode.XBIND_FAILED,message:e instanceof Error?e.message:"XBind exception",xbindError:e})}if(this.fallback){const e=await this.callViaFallback(a,r);return e.ok?(this.metrics.fallbackCalls++,this.updateMetrics("fallback"),e):err({code:DualModeErrorCode.FALLBACK_FAILED,message:"Fallback failed",fallbackError:e.error})}return err({code:DualModeErrorCode.INVALID_CONFIG,message:"Neither XBind nor fallback configured"})}getMetrics(){return{...this.metrics}}resetMetrics(){this.metrics={totalCalls:0,xbindCalls:0,fallbackCalls:0,xbindPercentage:0,lastCall:(new Date).toISOString(),lastCallMethod:"xbind"}}async callViaXBind(a,r){if(!this.xbind)return err({message:"XBind not configured"});try{const e=this.xbind.did;return await this.xbind.send({to:e,payload:{action:a,params:r},scope:a})}catch(a){return err({message:a instanceof Error?a.message:"Unknown error"})}}async callViaFallback(a,r){if(!this.fallback)return err({message:"Fallback not configured"});try{const e=`${this.fallback.url}/${a}`,t=this.fallback.method||"POST",l={"Content-Type":"application/json",...this.fallback.headers};"api-key"===this.fallback.type&&this.fallback.key&&(l.Authorization=`Bearer ${this.fallback.key}`);const i=await fetch(e,{method:t,headers:l,body:"GET"!==t?JSON.stringify(r):void 0});if(!i.ok)return err({message:`HTTP ${i.status}`});const s=await i.json();return ok(s)}catch(a){return err({message:a instanceof Error?a.message:"Network error"})}}updateMetrics(a){this.metrics.lastCall=(new Date).toISOString(),this.metrics.lastCallMethod=a,this.metrics.xbindPercentage=this.metrics.totalCalls>0?this.metrics.xbindCalls/this.metrics.totalCalls*100:0}}