import { endStreaming, initializeStreamingAnswer, setAnswer, setAnswerError, setAnswerId, setCitations, } from '../answer-draft-reducer/answer-draft-reducer.js';
/**
 * Manages answer server state updates during answer generation streaming.
 */
export const serverStateEventHandler = {
    handleOpen: (response, updateCachedData) => {
        const answerId = response.headers.get('x-answer-id');
        if (answerId) {
            updateCachedData((draft) => {
                setAnswerId(draft, answerId);
            });
        }
    },
    handleMessage: {
        'genqa.headerMessageType': (message, updateCachedData) => {
            const payload = parsePayload(message.payload);
            if (payload?.contentFormat) {
                updateCachedData((draft) => {
                    initializeStreamingAnswer(draft, payload);
                });
            }
        },
        'genqa.messageType': (message, updateCachedData) => {
            const payload = parsePayload(message.payload);
            if (payload.textDelta) {
                updateCachedData((draft) => {
                    setAnswer(draft, payload);
                });
            }
        },
        'genqa.citationsType': (message, updateCachedData) => {
            const payload = parsePayload(message.payload);
            if (payload.citations !== undefined) {
                updateCachedData((draft) => {
                    setCitations(draft, payload);
                });
            }
        },
        'genqa.endOfStreamType': (message, updateCachedData) => {
            const payload = parsePayload(message.payload);
            updateCachedData((draft) => {
                endStreaming(draft, payload);
            });
        },
        error: (message, updateCachedData) => {
            if (message.finishReason === 'ERROR') {
                updateCachedData((draft) => {
                    setAnswerError(draft, message);
                });
            }
        },
    },
};
function parsePayload(payload) {
    if (!payload?.length) {
        return {};
    }
    try {
        return JSON.parse(payload);
    }
    catch (err) {
        console.warn('Failed to parse stream payload', {
            payload,
            error: err,
        });
        return {};
    }
}
