import { SpanKind, SpanStatusCode } from '../types.js';
/**
 * Start a tool execution span as a child of the turn span.
 *
 * @param tracer - RuntimeTracer instance.
 * @param ctx - Tool span context from TOOL_RECEIVED event.
 */
export function startToolSpan(tracer, ctx) {
    const argsJson = ctx.args
        ? (() => {
            const raw = JSON.stringify(ctx.args);
            return raw.length > 512 ? raw.slice(0, 512) + '...' : raw;
        })()
        : '';
    const attrs = {
        'tool.name': ctx.tool,
        'tool.call_id': ctx.callId,
        'turn.id': ctx.turnId,
        'tool.args': argsJson,
    };
    return tracer.startSpan('tool.execute', {
        traceId: ctx.traceId,
        parentSpanId: ctx.parentSpanId,
        kind: SpanKind.INTERNAL,
        attributes: attrs,
    });
}
/**
 * Record a phase transition event on a tool span.
 *
 * @param span - The active tool span.
 * @param phase - The phase reached.
 * @param attrs - Optional additional attributes for this phase.
 */
export function recordToolPhase(span, phase, attrs) {
    if (span.ended)
        return;
    span.addEvent(`tool.${phase}`, attrs);
}
/**
 * End a tool execution span.
 *
 * @param span - The span returned by `startToolSpan`.
 * @param ctx - Tool end context.
 */
export function endToolSpan(span, ctx) {
    if (span.ended)
        return;
    span.setAttributes({
        'tool.outcome': ctx.outcome,
        'tool.duration_ms': ctx.durationMs,
    });
    if (ctx.approved !== undefined) {
        span.setAttribute('tool.approved', ctx.approved);
    }
    span.addEvent(`tool.${ctx.outcome}`);
    if (ctx.outcome === 'failed' && ctx.error) {
        span.setStatus({ code: SpanStatusCode.ERROR, message: ctx.error });
        span.setAttribute('tool.error', ctx.error);
    }
    else if (ctx.outcome === 'cancelled') {
        span.setStatus({ code: SpanStatusCode.OK });
        if (ctx.cancelReason) {
            span.setAttribute('tool.cancel_reason', ctx.cancelReason);
        }
    }
    else {
        span.setStatus({ code: SpanStatusCode.OK });
    }
    span.end();
}
