// SPEC: PJ2026-010401080313 Workbench realtime authority draft-2026-07-20-p0-kafka-sse-single-projection.
// Responsibility: Keep a retained Kafka replay invisible until its SSE live handoff is complete.

import type { WorkbenchRealtimeEvent } from "@/api/workbench-events";

export interface WorkbenchReplayVisibilityFrame {
  event: WorkbenchRealtimeEvent;
  eventName: string;
}

export class WorkbenchReplayVisibilityRuntime {
  private scopeKey: string | null = null;
  private frames: WorkbenchReplayVisibilityFrame[] = [];

  begin(scopeKey: string): void {
    this.scopeKey = scopeKey;
    this.frames = [];
  }

  stage(scopeKey: string, frame: WorkbenchReplayVisibilityFrame): boolean {
    if (scopeKey !== this.scopeKey || !isKafkaBusinessFrame(frame)) return false;
    this.frames.push(frame);
    return true;
  }

  commit(scopeKey: string): WorkbenchReplayVisibilityFrame[] {
    if (scopeKey !== this.scopeKey) return [];
    const frames = this.frames;
    this.scopeKey = null;
    this.frames = [];
    return frames;
  }

  discard(scopeKey?: string | null): void {
    if (scopeKey && scopeKey !== this.scopeKey) return;
    this.scopeKey = null;
    this.frames = [];
  }
}

export function createWorkbenchReplayVisibilityRuntime(): WorkbenchReplayVisibilityRuntime {
  return new WorkbenchReplayVisibilityRuntime();
}

function isKafkaBusinessFrame(frame: WorkbenchReplayVisibilityFrame): boolean {
  return frame.eventName === "hwlab.event.v1" || frame.event.schema === "hwlab.event.v1";
}
