import { SpanKind, SpanStatusCode } from '../types.js';
/**
 * Start an agent lifecycle span.
 *
 * @param tracer - RuntimeTracer instance.
 * @param ctx - Context from AGENT_SPAWNING event.
 */
export function startAgentSpan(tracer, ctx) {
    const attrs = {
        'agent.id': ctx.agentId,
        'agent.task': ctx.task.length > 256 ? ctx.task.slice(0, 256) + '...' : ctx.task,
    };
    if (ctx.taskId !== undefined) {
        attrs['task.id'] = ctx.taskId;
    }
    return tracer.startSpan('agent.lifecycle', {
        traceId: ctx.traceId,
        parentSpanId: ctx.parentSpanId,
        kind: SpanKind.INTERNAL,
        attributes: attrs,
    });
}
/**
 * Record an agent phase transition event.
 *
 * @param span - The active agent lifecycle span.
 * @param phase - The phase reached.
 * @param attrs - Optional additional attributes.
 */
export function recordAgentPhase(span, phase, attrs) {
    if (span.ended)
        return;
    span.addEvent(`agent.${phase}`, attrs);
}
/**
 * End an agent lifecycle span.
 *
 * @param span - The span returned by `startAgentSpan`.
 * @param ctx - Agent lifecycle end context.
 */
export function endAgentSpan(span, ctx) {
    if (span.ended)
        return;
    span.setAttributes({
        'agent.outcome': ctx.outcome,
        'agent.duration_ms': ctx.durationMs,
    });
    span.addEvent(`agent.${ctx.outcome}`);
    if (ctx.outcome === 'failed' && ctx.error) {
        span.setStatus({ code: SpanStatusCode.ERROR, message: ctx.error });
        span.setAttribute('agent.error', ctx.error);
    }
    else if (ctx.outcome === 'cancelled') {
        span.setStatus({ code: SpanStatusCode.OK });
        if (ctx.reason) {
            span.setAttribute('agent.cancel_reason', ctx.reason);
        }
    }
    else {
        span.setStatus({ code: SpanStatusCode.OK });
    }
    span.end();
}
