function generateEventBus(context) {
  const { spec } = context;
  const hasEvents = spec.events && Object.keys(spec.events).length > 0;
  const models = spec.models ? Object.keys(spec.models) : [];
  return `/**
 * Event Bus
 * Typed in-memory event bus using EventEmitter3
 * Generated from SpecVerse specification
 */

import { EventEmitter } from 'eventemitter3';
${hasEvents || models.length > 0 ? `import type { EventPayloads } from './event-types.js';` : ""}

// Re-export types for consumers
${hasEvents || models.length > 0 ? `export type { EventPayloads, EventName } from './event-types.js';` : ""}

/**
 * Event history entry
 */
interface EventHistoryEntry {
  event: string;
  payload: any;
  timestamp: Date;
}

/**
 * Event Bus Singleton
 */
class EventBus extends EventEmitter {
  private static instance: EventBus;
  private history: EventHistoryEntry[] = [];
  private maxHistory = 1000;

  private constructor() {
    super();
  }

  public static getInstance(): EventBus {
    if (!EventBus.instance) {
      EventBus.instance = new EventBus();
    }
    return EventBus.instance;
  }

  /**
   * Publish a typed event
   */
  public publish<K extends string>(event: K, payload: K extends keyof EventPayloads ? EventPayloads[K] : any): void {
    this.history.push({ event, payload, timestamp: new Date() });
    if (this.history.length > this.maxHistory) this.history.shift();
    this.emit(event, payload);
  }

  /**
   * Subscribe to a typed event
   */
  public subscribe<K extends string>(
    event: K,
    handler: (payload: K extends keyof EventPayloads ? EventPayloads[K] : any) => void | Promise<void>
  ): () => void {
    this.on(event, handler);
    return () => { this.off(event, handler); };
  }

  /**
   * Get event history
   */
  public getHistory(eventName?: string, limit = 50): EventHistoryEntry[] {
    const filtered = eventName
      ? this.history.filter(e => e.event === eventName)
      : this.history;
    return filtered.slice(-limit);
  }
}

// Export singleton instance
export const eventBus = EventBus.getInstance();
export default eventBus;
`;
}
export {
  generateEventBus as default
};
