export const TRACE_SOURCE_RANK = {
    transcript: 0,
    "event-log": 1,
    live: 2,
};
export const TRACE_PHASE_RANK = {
    "user.message": 0,
    "agent.turn": 1,
    "model.reasoning": 2,
    "tool.call": 3,
    "agent.delegation": 3,
    "agent.async": 4,
    "tool.result": 5,
    "execution.command": 6,
    "yielded.run": 7,
    "assistant.message": 8,
    error: 9,
};
export function transcriptTraceOrder(transcriptIndex, contentPartIndex, type) {
    return {
        sourceRank: TRACE_SOURCE_RANK.transcript,
        turnSeq: transcriptIndex,
        transcriptIndex,
        contentPartIndex,
        phaseRank: TRACE_PHASE_RANK[type],
    };
}
export function eventTraceOrder(eventSequence, type) {
    return {
        sourceRank: TRACE_SOURCE_RANK["event-log"],
        turnSeq: eventSequence ?? Number.MAX_SAFE_INTEGER,
        eventSequence,
        phaseRank: TRACE_PHASE_RANK[type],
    };
}
export function liveTraceOrder(streamId, streamFrameIndex, type) {
    const streamOrder = streamId ?? Number.MAX_SAFE_INTEGER;
    const frameIndex = streamFrameIndex ?? Number.MAX_SAFE_INTEGER;
    return {
        sourceRank: TRACE_SOURCE_RANK.live,
        turnSeq: streamOrder,
        streamId: streamOrder,
        streamFrameIndex: frameIndex,
        phaseRank: TRACE_PHASE_RANK[type],
    };
}
export function parseTraceStreamFrameId(value) {
    const [stream, frame] = value.split(":");
    if (stream === undefined || frame === undefined)
        return undefined;
    const streamId = Number(stream);
    const frameIndex = Number(frame);
    if (!Number.isInteger(streamId) || streamId < 0)
        return undefined;
    if (!Number.isInteger(frameIndex) || frameIndex < 0)
        return undefined;
    return { streamId, frameIndex };
}
export function childTraceOrder(parent, type) {
    if (!parent)
        return undefined;
    return {
        ...parent,
        contentPartIndex: (parent.contentPartIndex ?? 0) + 0.1,
        phaseRank: TRACE_PHASE_RANK[type],
    };
}
export function compareTraceOrder(left, right) {
    if (!left && !right)
        return 0;
    if (!left)
        return 1;
    if (!right)
        return -1;
    return (left.turnSeq - right.turnSeq ||
        (left.transcriptIndex ?? Number.MAX_SAFE_INTEGER) - (right.transcriptIndex ?? Number.MAX_SAFE_INTEGER) ||
        (left.eventSequence ?? Number.MAX_SAFE_INTEGER) - (right.eventSequence ?? Number.MAX_SAFE_INTEGER) ||
        (left.streamId ?? Number.MAX_SAFE_INTEGER) - (right.streamId ?? Number.MAX_SAFE_INTEGER) ||
        (left.streamFrameIndex ?? Number.MAX_SAFE_INTEGER) - (right.streamFrameIndex ?? Number.MAX_SAFE_INTEGER) ||
        (left.contentPartIndex ?? 0) - (right.contentPartIndex ?? 0) ||
        left.phaseRank - right.phaseRank ||
        left.sourceRank - right.sourceRank);
}
