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