import {
  markerReleaseTime,
  resolvePressSampleKey,
  resolveReleaseSampleKey,
  type SoundPhase,
  type SwitchManifest,
} from './keySoundMap';
import type { Marker } from '../types';

/** A single press or release sample placed on the video timeline (seconds, 1×). */
export type ScheduledEvent = {
  phase: SoundPhase;
  sampleKey: string;
  /** Video-timeline seconds — never adjusted for preview playback speed. */
  time: number;
};

/**
 * Build a sorted list of press/release events from markers.
 * Times are absolute video coordinates used by both preview scheduling and 1× export.
 */
export function buildMarkerSchedule(
  markers: Marker[],
  switchEntry: SwitchManifest,
): ScheduledEvent[] {
  const events: ScheduledEvent[] = [];

  for (const marker of markers) {
    const code = marker.code ?? marker.key;
    events.push({
      phase: 'press',
      sampleKey: resolvePressSampleKey(marker.key, code, switchEntry.press),
      time: marker.time,
    });
    events.push({
      phase: 'release',
      sampleKey: resolveReleaseSampleKey(marker.key, switchEntry.release),
      time: markerReleaseTime(marker),
    });
  }

  return events.sort((a, b) => a.time - b.time);
}
