import{DiagnosticSizes as b}from"./options.js";import{MT as s,NUMBYTES as f,SYMS as d}from"./constants.js";import{CBORcontainer as S}from"./container.js";import{DecodeStream as E}from"./decodeStream.js";import{Simple as N}from"./simple.js";import{halfToUint as I}from"./float.js";import{u8toHex as _}from"./utils.js";const O="  ",y=new TextEncoder;class g extends S{close="";quote='"';get isEmptyStream(){return(this.mt===s.UTF8_STRING||this.mt===s.BYTE_STRING)&&this.count===0}}function a(m,l,n,p){let t="";if(l===f.INDEFINITE)t+="_";else{if(p.diagnosticSizes===b.NEVER)return"";{let r=p.diagnosticSizes===b.ALWAYS;if(!r){let e=f.ZERO;if(Object.is(n,-0))e=f.TWO;else if(m===s.POS_INT||m===s.NEG_INT){const T=n<0,u=typeof n=="bigint"?1n:1,o=T?-n-u:n;o<=23?e=Number(o):o<=255?e=f.ONE:o<=65535?e=f.TWO:o<=4294967295?e=f.FOUR:e=f.EIGHT}else isFinite(n)?Math.fround(n)===n?I(n)==null?e=f.FOUR:e=f.TWO:e=f.EIGHT:e=f.TWO;r=e!==l}r&&(t+="_",l<f.ONE?t+="i":t+=String(l-24))}}return t}function M(m,l){const n={...S.defaultDecodeOptions,...l,ParentType:g},p=new E(m,n);let t,r,e="";for(const T of p){const[u,o,i]=T;switch(t&&(t.count>0&&i!==d.BREAK&&(t.mt===s.MAP&&t.count%2?e+=": ":(e+=",",n.pretty||(e+=" "))),n.pretty&&(t.mt!==s.MAP||t.count%2===0)&&(e+=`
${O.repeat(t.depth+1)}`)),r=S.create(T,t,n,p),u){case s.POS_INT:case s.NEG_INT:e+=String(i),e+=a(u,o,i,n);break;case s.SIMPLE_FLOAT:if(i!==d.BREAK)if(typeof i=="number"){const c=Object.is(i,-0)?"-0.0":String(i);e+=c,isFinite(i)&&!/[.e]/.test(c)&&(e+=".0"),e+=a(u,o,i,n)}else i instanceof N?(e+="simple(",e+=String(i.value),e+=a(s.POS_INT,o,i.value,n),e+=")"):e+=String(i);break;case s.BYTE_STRING:i===1/0?(e+="(_ ",r.close=")",r.quote="'"):(e+="h'",e+=_(i),e+="'",e+=a(s.POS_INT,o,i.length,n));break;case s.UTF8_STRING:i===1/0?(e+="(_ ",r.close=")"):(e+=JSON.stringify(i),e+=a(s.POS_INT,o,y.encode(i).length,n));break;case s.ARRAY:{e+="[";const c=a(s.POS_INT,o,i,n);e+=c,c&&(e+=" "),n.pretty&&i?r.close=`
${O.repeat(r.depth)}]`:r.close="]";break}case s.MAP:{e+="{";const c=a(s.POS_INT,o,i,n);e+=c,c&&(e+=" "),n.pretty&&i?r.close=`
${O.repeat(r.depth)}}`:r.close="}";break}case s.TAG:e+=String(i),e+=a(s.POS_INT,o,i,n),e+="(",r.close=")";break}if(r===d.BREAK)if(t?.isStreaming)t.left=0;else throw new Error("Unexpected BREAK");else t&&(t.count++,t.left--);for(r instanceof g&&(t=r);t?.done;){if(t.isEmptyStream)e=e.slice(0,-3),e+=`${t.quote}${t.quote}_`;else{if(t.mt===s.MAP&&t.count%2!==0)throw new Error(`Odd streaming map size: ${t.count}`);e+=t.close}t=t.parent}}return e}export{M as diagnose};
