import { SpanKind, SpanStatusCode } from '../types.js';
/**
 * Start a transport lifecycle span.
 *
 * @param tracer - RuntimeTracer instance.
 * @param ctx - Context from TRANSPORT_INITIALIZING event.
 */
export function startTransportSpan(tracer, ctx) {
    const attrs = {
        'transport.id': ctx.transportId,
        'transport.protocol': ctx.protocol,
    };
    return tracer.startSpan('transport.lifecycle', {
        traceId: ctx.traceId,
        kind: SpanKind.CLIENT,
        attributes: attrs,
    });
}
/**
 * Record a transport phase transition event.
 *
 * @param span - The active transport lifecycle span.
 * @param phase - The phase reached.
 * @param attrs - Optional additional attributes.
 */
export function recordTransportPhase(span, phase, attrs) {
    if (span.ended)
        return;
    span.addEvent(`transport.${phase}`, attrs);
}
/**
 * End a transport lifecycle span.
 *
 * @param span - The span returned by `startTransportSpan`.
 * @param ctx - Transport lifecycle end context.
 */
export function endTransportSpan(span, ctx) {
    if (span.ended)
        return;
    span.setAttribute('transport.outcome', ctx.outcome);
    if (ctx.endpoint !== undefined) {
        span.setAttribute('transport.endpoint', ctx.endpoint);
    }
    if (ctx.willRetry !== undefined) {
        span.setAttribute('transport.will_retry', ctx.willRetry);
    }
    span.addEvent(`transport.${ctx.outcome}`);
    if (ctx.outcome === 'terminal_failure') {
        const msg = ctx.reason ?? 'Transport terminal failure';
        span.setStatus({ code: SpanStatusCode.ERROR, message: msg });
        span.setAttribute('transport.error', msg);
    }
    else if (ctx.outcome === 'disconnected' && !ctx.willRetry) {
        span.setStatus({ code: SpanStatusCode.ERROR, message: ctx.reason ?? 'Transport disconnected' });
        if (ctx.reason) {
            span.setAttribute('transport.disconnect_reason', ctx.reason);
        }
    }
    else {
        span.setStatus({ code: SpanStatusCode.OK });
    }
    span.end();
}
