function generateWebSocketBridge(context) {
  const { spec } = context;
  const models = spec.models ? Object.keys(spec.models) : [];
  const specEvents = spec.events ? Object.keys(spec.events) : [];
  const curedEvents = models.flatMap(
    (m) => ["Created", "Updated", "Deleted", "Evolved"].map((s) => `${m}${s}`)
  );
  const allEvents = [.../* @__PURE__ */ new Set([...specEvents, ...curedEvents])];
  return `/**
 * WebSocket Bridge
 * Bridges the event bus to frontend clients for real-time updates.
 * Generated from SpecVerse specification
 */

import type { FastifyInstance } from 'fastify';
import type { WebSocket } from '@fastify/websocket';
import { eventBus } from './eventBus.js';

interface ClientSubscription {
  ws: WebSocket;
  events: Set<string>;
}

const clients = new Map<WebSocket, ClientSubscription>();

// All events this bridge knows about
const ALL_EVENTS = ${JSON.stringify(allEvents, null, 2)};

/**
 * Register WebSocket bridge with Fastify
 */
export async function registerWebSocketBridge(fastify: FastifyInstance): Promise<void> {
  // Register @fastify/websocket plugin
  const websocketPlugin = await import('@fastify/websocket');
  await fastify.register(websocketPlugin.default || websocketPlugin);

  // WebSocket route
  fastify.get('/ws', { websocket: true }, (socket: WebSocket) => {
    const subscription: ClientSubscription = { ws: socket, events: new Set() };
    clients.set(socket, subscription);

    socket.on('message', (raw: Buffer) => {
      try {
        const msg = JSON.parse(raw.toString());

        if (msg.type === 'subscribe' && msg.event) {
          subscription.events.add(msg.event);
          socket.send(JSON.stringify({ type: 'subscribed', event: msg.event }));
        }

        if (msg.type === 'unsubscribe' && msg.event) {
          subscription.events.delete(msg.event);
          socket.send(JSON.stringify({ type: 'unsubscribed', event: msg.event }));
        }

        if (msg.type === 'subscribe-all') {
          ALL_EVENTS.forEach(e => subscription.events.add(e));
          socket.send(JSON.stringify({ type: 'subscribed-all', events: ALL_EVENTS }));
        }
      } catch { /* ignore malformed messages */ }
    });

    socket.on('close', () => {
      clients.delete(socket);
    });

    // Send initial connection confirmation
    socket.send(JSON.stringify({
      type: 'connected',
      availableEvents: ALL_EVENTS,
    }));
  });

  // Subscribe to all events and broadcast to interested clients
  for (const eventName of ALL_EVENTS) {
    eventBus.subscribe(eventName, (payload: any) => {
      const message = JSON.stringify({
        type: 'event',
        event: eventName,
        payload,
        timestamp: new Date().toISOString(),
      });

      for (const [ws, sub] of clients) {
        if (sub.events.has(eventName) && ws.readyState === 1) {
          try { ws.send(message); } catch { /* client disconnected */ }
        }
      }
    });
  }
}
`;
}
export {
  generateWebSocketBridge as default
};
