import { SpanKind, SpanStatusCode } from '../types.js';
/**
 * Start a plugin lifecycle span.
 *
 * @param tracer - RuntimeTracer instance.
 * @param ctx - Context from PLUGIN_DISCOVERED event.
 */
export function startPluginSpan(tracer, ctx) {
    const attrs = {
        'plugin.id': ctx.pluginId,
        'plugin.path': ctx.path,
        'plugin.version': ctx.version,
    };
    return tracer.startSpan('plugin.lifecycle', {
        traceId: ctx.traceId,
        kind: SpanKind.INTERNAL,
        attributes: attrs,
    });
}
/**
 * Record a plugin phase transition event on the active span.
 *
 * @param span - The active plugin lifecycle span.
 * @param phase - The phase reached.
 * @param attrs - Optional additional attributes for this phase.
 */
export function recordPluginPhase(span, phase, attrs) {
    if (span.ended)
        return;
    span.addEvent(`plugin.${phase}`, attrs);
}
/**
 * End a plugin lifecycle span.
 *
 * @param span - The span returned by `startPluginSpan`.
 * @param ctx - Plugin lifecycle end context.
 */
export function endPluginSpan(span, ctx) {
    if (span.ended)
        return;
    span.setAttribute('plugin.outcome', ctx.outcome);
    if (ctx.capabilities !== undefined) {
        span.setAttribute('plugin.capability_count', ctx.capabilities.length);
    }
    span.addEvent(`plugin.${ctx.outcome}`);
    if (ctx.outcome === 'error' && ctx.error) {
        span.setStatus({ code: SpanStatusCode.ERROR, message: ctx.error });
        span.setAttribute('plugin.error', ctx.error);
    }
    else if (ctx.outcome === 'disabled') {
        span.setStatus({ code: SpanStatusCode.OK });
        if (ctx.reason) {
            span.setAttribute('plugin.disable_reason', ctx.reason);
        }
    }
    else {
        span.setStatus({ code: SpanStatusCode.OK });
    }
    span.end();
}
