import { SpanKind, SpanStatusCode } from '../types.js';
/**
 * Start a permission decision span.
 *
 * @param tracer - RuntimeTracer instance.
 * @param ctx - Context from PERMISSION_REQUESTED event.
 */
export function startPermissionSpan(tracer, ctx) {
    const attrs = {
        'permission.call_id': ctx.callId,
        'permission.tool': ctx.tool,
        'permission.category': ctx.category,
    };
    return tracer.startSpan('permission.decision', {
        traceId: ctx.traceId,
        parentSpanId: ctx.parentSpanId,
        kind: SpanKind.INTERNAL,
        attributes: attrs,
    });
}
/**
 * Record a permission evaluation phase transition.
 *
 * @param span - The active permission decision span.
 * @param phase - The phase reached.
 * @param attrs - Optional additional attributes.
 */
export function recordPermissionPhase(span, phase, attrs) {
    if (span.ended)
        return;
    span.addEvent(`permission.${phase}`, attrs);
}
/**
 * End a permission decision span.
 *
 * @param span - The span returned by `startPermissionSpan`.
 * @param ctx - Permission decision end context.
 */
export function endPermissionSpan(span, ctx) {
    if (span.ended)
        return;
    span.setAttributes({
        'permission.approved': ctx.approved,
        'permission.source': ctx.source,
    });
    if (ctx.safe !== undefined) {
        span.setAttribute('permission.safe', ctx.safe);
    }
    if (ctx.warnings !== undefined && ctx.warnings.length > 0) {
        span.setAttribute('permission.warning_count', ctx.warnings.length);
    }
    span.addEvent(ctx.approved ? 'permission.approved' : 'permission.denied');
    if (!ctx.approved) {
        span.setStatus({
            code: SpanStatusCode.ERROR,
            message: `Permission denied by ${ctx.source}`,
        });
    }
    else {
        span.setStatus({ code: SpanStatusCode.OK });
    }
    span.end();
}
