import { SpanKind, SpanStatusCode } from '../types.js';
/**
 * Start an MCP server lifecycle span.
 *
 * @param tracer - RuntimeTracer instance.
 * @param ctx - Context from MCP_CONFIGURED event.
 */
export function startMcpSpan(tracer, ctx) {
    const attrs = {
        'mcp.server_id': ctx.serverId,
        'mcp.transport': ctx.transport,
    };
    if (ctx.url !== undefined) {
        attrs['mcp.url'] = ctx.url;
    }
    return tracer.startSpan('mcp.lifecycle', {
        traceId: ctx.traceId,
        kind: SpanKind.CLIENT,
        attributes: attrs,
    });
}
/**
 * Record an MCP server phase transition event.
 *
 * @param span - The active MCP lifecycle span.
 * @param phase - The phase reached.
 * @param attrs - Optional additional attributes.
 */
export function recordMcpPhase(span, phase, attrs) {
    if (span.ended)
        return;
    span.addEvent(`mcp.${phase}`, attrs);
}
/**
 * End an MCP server lifecycle span.
 *
 * @param span - The span returned by `startMcpSpan`.
 * @param ctx - MCP lifecycle end context.
 */
export function endMcpSpan(span, ctx) {
    if (span.ended)
        return;
    span.setAttribute('mcp.outcome', ctx.outcome);
    if (ctx.toolCount !== undefined) {
        span.setAttribute('mcp.tool_count', ctx.toolCount);
    }
    if (ctx.resourceCount !== undefined) {
        span.setAttribute('mcp.resource_count', ctx.resourceCount);
    }
    if (ctx.willRetry !== undefined) {
        span.setAttribute('mcp.will_retry', ctx.willRetry);
    }
    span.addEvent(`mcp.${ctx.outcome}`);
    if (ctx.outcome === 'auth_failed') {
        span.setStatus({ code: SpanStatusCode.ERROR, message: 'MCP authentication failed' });
    }
    else if (ctx.outcome === 'disconnected' && !ctx.willRetry) {
        span.setStatus({ code: SpanStatusCode.ERROR, message: ctx.reason ?? 'MCP disconnected' });
        if (ctx.reason) {
            span.setAttribute('mcp.disconnect_reason', ctx.reason);
        }
    }
    else {
        span.setStatus({ code: SpanStatusCode.OK });
    }
    span.end();
}
