// Separate client sets for different SSE streams
const windowClients = new Set();
/**
 * Set up SSE headers and return a client object
 */
export function setupSSE(res, clientId) {
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');
    res.flushHeaders();
    return { res, clientId };
}
/**
 * Send an SSE message to a client
 */
export function sendSSE(client, data) {
    try {
        client.res.write(`data: ${JSON.stringify(data)}\n\n`);
        return true;
    }
    catch {
        return false;
    }
}
// ===== Window SSE management =====
export function addWindowClient(client) {
    windowClients.add(client);
    console.log(`[sse] Window client connected (${windowClients.size} total)`);
}
export function removeWindowClient(client) {
    windowClients.delete(client);
    console.log(`[sse] Window client disconnected (${windowClients.size} total)`);
}
export function broadcastWindowEvent(message, excludeClientId) {
    for (const client of windowClients) {
        // Don't echo back to the source client
        if (excludeClientId && client.clientId === excludeClientId) {
            continue;
        }
        if (!sendSSE(client, message)) {
            windowClients.delete(client);
        }
    }
}
