import { SpanKind, SpanStatusCode } from '../types.js';
/**
 * Start a session lifecycle span.
 *
 * @param tracer - RuntimeTracer instance.
 * @param ctx - Context from SESSION_STARTED or SESSION_LOADING event.
 */
export function startSessionSpan(tracer, ctx) {
    const attrs = {
        'session.id': ctx.sessionId,
    };
    if (ctx.profileId !== undefined) {
        attrs['session.profile_id'] = ctx.profileId;
    }
    if (ctx.workingDir !== undefined) {
        attrs['session.working_dir'] = ctx.workingDir;
    }
    if (ctx.path !== undefined) {
        attrs['session.path'] = ctx.path;
    }
    return tracer.startSpan('session.lifecycle', {
        traceId: ctx.traceId,
        kind: SpanKind.INTERNAL,
        attributes: attrs,
    });
}
/**
 * Record a session lifecycle phase transition.
 *
 * @param span - The active session lifecycle span.
 * @param phase - The phase reached.
 * @param attrs - Optional additional attributes.
 */
export function recordSessionPhase(span, phase, attrs) {
    if (span.ended)
        return;
    span.addEvent(`session.${phase}`, attrs);
}
/**
 * End a session lifecycle span.
 *
 * @param span - The span returned by `startSessionSpan`.
 * @param ctx - Session lifecycle end context.
 */
export function endSessionSpan(span, ctx) {
    if (span.ended)
        return;
    span.setAttribute('session.outcome', ctx.outcome);
    if (ctx.turnCount !== undefined) {
        span.setAttribute('session.turn_count', ctx.turnCount);
    }
    if (ctx.messageCount !== undefined) {
        span.setAttribute('session.message_count', ctx.messageCount);
    }
    span.addEvent(`session.${ctx.outcome}`);
    if (ctx.outcome === 'recovery_failed' && ctx.error) {
        span.setStatus({ code: SpanStatusCode.ERROR, message: ctx.error });
        span.setAttribute('session.error', ctx.error);
    }
    else {
        span.setStatus({ code: SpanStatusCode.OK });
    }
    span.end();
}
