import {normalizeWallexMarkets,normalizeWallexCandles,normalizeWallexDepth,type WallexFeed,type WallexSymbol,type WallexDetail} from './wallex';
const origin='https://api.wallex.ir';
async function provider(path:string){
 const response=await fetch(origin+path,{headers:{Accept:'application/json','Content-Type':'application/json'},cache:'no-store',redirect:'manual',signal:AbortSignal.timeout(8000)});
 if(!response.ok)throw new Error('wallex_unavailable');
 return response.json() as Promise<unknown>;
}
let cache:WallexFeed|null=null,pending:Promise<WallexFeed>|null=null,retryAt=0;
export async function getWallexMarkets():Promise<WallexFeed>{
 if(cache?.receivedAt&&Date.now()-Date.parse(cache.receivedAt)<20000)return cache;
 if(pending)return pending;
 if(Date.now()<retryAt)return {source:'wallex',status:'unavailable',quotes:[],receivedAt:null,error:'دریافت اطلاعات والکس ممکن نشد. کمی بعد دوباره تلاش کنید.'};
 pending=(async()=>{try{const payload=await provider('/hector/web/v1/markets');cache=normalizeWallexMarkets(payload,new Date().toISOString());return cache}catch{console.error('wallex_feed_failed');retryAt=Date.now()+10000;return {source:'wallex',status:'unavailable',quotes:[],receivedAt:null,error:'دریافت اطلاعات والکس ممکن نشد. کمی بعد دوباره تلاش کنید.'} as WallexFeed}finally{pending=null}})();
 return pending;
}
const details=new Map<string,{expires:number;data:Promise<WallexDetail>}>();
export function getWallexDetail(symbol:WallexSymbol):Promise<WallexDetail>{
 const previous=details.get(symbol);if(previous&&previous.expires>Date.now())return previous.data;
 const to=Math.floor(Date.now()/1000),from=to-86400;
 const data=(async()=>{const [history,depth]=await Promise.allSettled([provider(`/v1/udf/history?symbol=${symbol}&resolution=60&from=${from}&to=${to}`),provider(`/v1/depth?symbol=${symbol}`)]);
 const candles=history.status==='fulfilled'?normalizeWallexCandles(history.value,from,to):[];
 return {symbol,receivedAt:new Date().toISOString(),candles,historyAvailable:candles.length>1,...normalizeWallexDepth(depth.status==='fulfilled'?depth.value:null)};
 })();details.set(symbol,{expires:Date.now()+60000,data});return data;
}
