import { useMemo } from "react";
import { getAgentRunMessageAgentId, getAgentRunMessageDetail, getAgentRunMessageSeq, isHeartbeatRunEventMessage, normalizeDialogAgentId, } from "../agentMessageHelpers";
const RECENT_RUN_EVENTS_LIMIT = 50;
const EMPTY_RUN_DIAGNOSTICS = {
    events: [],
    totalCount: 0,
    receivedSeqs: [],
    missingSeqs: [],
};
export function useAgentRunDiagnostics(input) {
    const { agentId, webSocketMessages } = input;
    return useMemo(() => {
        const normalizedAgentId = normalizeDialogAgentId(agentId);
        if (!normalizedAgentId) {
            return EMPTY_RUN_DIAGNOSTICS;
        }
        const agentRunMessages = (webSocketMessages || []).filter((message) => {
            if (!message?.type?.startsWith("agent:run:")) {
                return false;
            }
            if (isHeartbeatRunEventMessage(message)) {
                return false;
            }
            return getAgentRunMessageAgentId(message.payload) === normalizedAgentId;
        });
        let runStartIndex = 0;
        for (let i = agentRunMessages.length - 1; i >= 0; i--) {
            if (agentRunMessages[i]?.type === "agent:run:start") {
                runStartIndex = i;
                break;
            }
        }
        const currentRunMessages = agentRunMessages.slice(runStartIndex);
        const seqsSet = new Set();
        for (const message of currentRunMessages) {
            const seq = message.seq ?? getAgentRunMessageSeq(message.payload);
            if (typeof seq === "number" && seq > 0) {
                seqsSet.add(seq);
            }
        }
        const receivedSeqs = [...seqsSet].sort((a, b) => a - b);
        const missingSeqs = [];
        const max = receivedSeqs[receivedSeqs.length - 1];
        if (max !== undefined) {
            for (let i = 1; i <= max; i++) {
                if (!seqsSet.has(i))
                    missingSeqs.push(i);
            }
        }
        const events = currentRunMessages
            .slice(-RECENT_RUN_EVENTS_LIMIT)
            .map((message) => ({
            timestamp: message.timestamp,
            direction: message.direction ?? "incoming",
            type: message.type,
            seq: message.seq ?? getAgentRunMessageSeq(message.payload),
            detail: message.detail ??
                getAgentRunMessageDetail(message.type, message.payload),
            rawMessage: message.rawMessage,
            payloadBytes: message.payloadBytes ?? null,
        }));
        return {
            events,
            totalCount: currentRunMessages.length,
            receivedSeqs,
            missingSeqs,
        };
    }, [agentId, webSocketMessages]);
}
//# sourceMappingURL=useAgentRunDiagnostics.js.map