import{TraceContext,generateSpanId}from"./trace-context.js";export var SpanStatusCode;!function(t){t[t.OK=0]="OK",t[t.ERROR=1]="ERROR",t[t.UNSET=2]="UNSET"}(SpanStatusCode||(SpanStatusCode={}));export var SpanKind;!function(t){t[t.INTERNAL=0]="INTERNAL",t[t.SERVER=1]="SERVER",t[t.CLIENT=2]="CLIENT",t[t.PRODUCER=3]="PRODUCER",t[t.CONSUMER=4]="CONSUMER"}(SpanKind||(SpanKind={}));export class TraceSpan{spanId;traceContext;name;kind;parentSpanId;startTime;endTime;status;attributes;events;ended;constructor(t,e,n={}){this.spanId=generateSpanId(),this.traceContext=e,this.name=t,this.kind=n.kind??SpanKind.INTERNAL,this.parentSpanId=n.parentSpanId,this.startTime=Date.now(),this.status={code:SpanStatusCode.UNSET},this.attributes=n.attributes??{},this.events=[],this.ended=!1}setAttribute(t,e){if(this.ended)throw new Error("Cannot set attribute on ended span");return this.attributes[t]=e,this}setAttributes(t){if(this.ended)throw new Error("Cannot set attributes on ended span");return Object.assign(this.attributes,t),this}addEvent(t,e){if(this.ended)throw new Error("Cannot add event to ended span");return this.events.push({name:t,timestamp:Date.now(),attributes:e}),this}setStatus(t,e){if(this.ended)throw new Error("Cannot set status on ended span");return this.status={code:t,message:e},this}recordException(t){if(this.ended)throw new Error("Cannot record exception on ended span");this.setStatus(SpanStatusCode.ERROR);const e={};return t instanceof Error?(e["exception.type"]=t.name,e["exception.message"]=t.message,t.stack&&(e["exception.stacktrace"]=t.stack)):e["exception.message"]=String(t),this.addEvent("exception",e),this}end(t){this.ended||(this.endTime=t??Date.now(),this.ended=!0,this.status.code===SpanStatusCode.UNSET&&(this.status={code:SpanStatusCode.OK}))}isEnded(){return this.ended}getDuration(){return this.ended&&this.endTime?this.endTime-this.startTime:null}toData(){if(!this.ended||!this.endTime)throw new Error("Cannot export data from active span. Call end() first.");return{spanId:this.spanId,traceId:this.traceContext.traceId,parentSpanId:this.parentSpanId,name:this.name,kind:this.kind,startTime:this.startTime,endTime:this.endTime,duration:this.endTime-this.startTime,status:{...this.status},attributes:{...this.attributes},events:this.events.map(t=>({name:t.name,timestamp:t.timestamp,attributes:t.attributes?{...t.attributes}:void 0}))}}createChild(t,e={}){return new TraceSpan(t,this.traceContext,{...e,parentSpanId:this.spanId})}}export class SpanRecorder{activeSpans;completedSpans;maxSpans;rootContext;constructor(t={}){this.activeSpans=new Map,this.completedSpans=[],this.maxSpans=t.maxSpans??1e3,this.rootContext=t.traceContext}startSpan(t,e={}){const n=e.traceContext??e.parentSpan?.traceContext??this.rootContext??TraceContext.create(),a=new TraceSpan(t,n,{kind:e.kind,attributes:e.attributes,parentSpanId:e.parentSpan?.spanId});this.activeSpans.set(a.spanId,a);const s=setTimeout(()=>{a.isEnded()||(a.setStatus(SpanStatusCode.ERROR,"Span not ended (auto-ended by recorder)"),this.endSpan(a))},6e4),r=a.end.bind(a);return a.end=t=>{clearTimeout(s),r(t),this.endSpan(a)},a}endSpan(t){t.isEnded()||t.end(),this.activeSpans.delete(t.spanId);const e=t.toData();this.completedSpans.push(e),this.completedSpans.length>this.maxSpans&&this.completedSpans.shift()}getCompletedSpans(){return[...this.completedSpans]}getActiveSpans(){return Array.from(this.activeSpans.values())}clearCompletedSpans(){this.completedSpans=[]}getSpanCount(){return{active:this.activeSpans.size,completed:this.completedSpans.length}}findSpansByTraceId(t){return this.completedSpans.filter(e=>e.traceId===t)}buildTraceTree(t){const e=this.findSpansByTraceId(t);if(0===e.length)return null;const n=e.find(t=>!t.parentSpanId);return n?buildSpanTreeNode(n,e):null}}function buildSpanTreeNode(t,e){const n=e.filter(e=>e.parentSpanId===t.spanId).map(t=>buildSpanTreeNode(t,e));return{span:t,children:n}}export async function measureAsync(t,e,n,a){const s=t.startSpan(e,a);try{const t=await n();return s.setStatus(SpanStatusCode.OK),t}catch(t){throw s.recordException(t),t}finally{s.end()}}export function measureSync(t,e,n,a){const s=t.startSpan(e,a);try{const t=n();return s.setStatus(SpanStatusCode.OK),t}catch(t){throw s.recordException(t),t}finally{s.end()}}