import { EventEmitter } from 'events';

export interface JobStreamEvent {
  type: 'prompt_progress' | 'text' | 'tool_use' | 'tool_use_delta' | 'tool_result' | 'done';
  // prompt_progress
  processed?: number;
  total?: number;
  timeMs?: number;
  cache?: number;
  // text
  text?: string;
  // tool_use / tool_result
  toolName?: string;
  toolInput?: string;
  toolOutput?: string;
  toolIsError?: boolean;
  callId?: string;
  // tool_use_delta (live tool-call argument streaming)
  name?: string;
  chunk?: string;
}

class JobEventBus extends EventEmitter {
  constructor() {
    super();
    this.setMaxListeners(200);
  }

  emitJob(jobId: string, event: JobStreamEvent): void {
    this.emit(`job:${jobId}`, event);
  }

  onJob(jobId: string, handler: (event: JobStreamEvent) => void): void {
    this.on(`job:${jobId}`, handler);
  }

  offJob(jobId: string, handler: (event: JobStreamEvent) => void): void {
    this.off(`job:${jobId}`, handler);
  }

  hasListeners(jobId: string): boolean {
    return this.listenerCount(`job:${jobId}`) > 0;
  }
}

export const jobEventBus = new JobEventBus();
