import { SpanKind, SpanStatusCode } from '../types.js';
/**
 * Start a compaction lifecycle span.
 *
 * @param tracer - RuntimeTracer instance.
 * @param ctx - Context from COMPACTION_CHECK, COMPACTION_AUTOCOMPACT, or COMPACTION_REACTIVE.
 */
export function startCompactionSpan(tracer, ctx) {
    const attrs = {
        'compaction.session_id': ctx.sessionId,
        'compaction.strategy': ctx.strategy,
        'compaction.tokens_before': ctx.tokenCount,
    };
    if (ctx.threshold !== undefined) {
        attrs['compaction.threshold'] = ctx.threshold;
    }
    if (ctx.limit !== undefined) {
        attrs['compaction.limit'] = ctx.limit;
    }
    return tracer.startSpan('compaction.lifecycle', {
        traceId: ctx.traceId,
        kind: SpanKind.INTERNAL,
        attributes: attrs,
    });
}
/**
 * Record a compaction phase transition event.
 *
 * @param span - The active compaction lifecycle span.
 * @param phase - The phase reached.
 * @param attrs - Optional additional attributes.
 */
export function recordCompactionPhase(span, phase, attrs) {
    if (span.ended)
        return;
    span.addEvent(`compaction.${phase}`, attrs);
}
/**
 * End a compaction lifecycle span.
 *
 * @param span - The span returned by `startCompactionSpan`.
 * @param ctx - Compaction lifecycle end context.
 */
export function endCompactionSpan(span, ctx) {
    if (span.ended)
        return;
    span.setAttributes({
        'compaction.outcome': ctx.outcome,
        'compaction.tokens_before': ctx.tokensBefore,
    });
    if (ctx.tokensAfter !== undefined) {
        span.setAttribute('compaction.tokens_after', ctx.tokensAfter);
        span.setAttribute('compaction.tokens_saved', ctx.tokensBefore - ctx.tokensAfter);
    }
    if (ctx.durationMs !== undefined) {
        span.setAttribute('compaction.duration_ms', ctx.durationMs);
    }
    if (ctx.checkpointId !== undefined) {
        span.setAttribute('compaction.checkpoint_id', ctx.checkpointId);
    }
    span.addEvent(`compaction.${ctx.outcome}`);
    if (ctx.outcome === 'failed' && ctx.error) {
        span.setStatus({ code: SpanStatusCode.ERROR, message: ctx.error });
        span.setAttribute('compaction.error', ctx.error);
    }
    else {
        span.setStatus({ code: SpanStatusCode.OK });
    }
    span.end();
}
