// Build FFmpeg `volume` filter expression from a list of keyframes.
//
// The volume filter expression language evaluates once per audio sample:
//   - `t` is the current timestamp in seconds
//   - `between(t, start, end)` is true when t is in [start, end]
//   - `lerp(a, b, x)` is linear interpolation between a and b
//
// We translate each adjacent keyframe pair into a `between + lerp` segment
// and AND them all. The fallback is the clip's static volume.

import type { VolumeKeyframe } from '@/types';

export function buildVolumeExpression(
  kf: VolumeKeyframe[] | undefined,
  clipVolume: number,
): string {
  if (!kf || kf.length === 0) return String(clipVolume);
  const sorted = [...kf].sort((a, b) => a.time - b.time);
  const segments: string[] = [];
  for (let i = 0; i < sorted.length - 1; i++) {
    const a = sorted[i];
    const b = sorted[i + 1];
    if (b.time <= a.time) continue;
    segments.push(
      `between(t,${a.time.toFixed(3)},${b.time.toFixed(3)})*` +
        `lerp(${a.value.toFixed(3)},${b.value.toFixed(3)},` +
        `(t-${a.time.toFixed(3)})/${(b.time - a.time).toFixed(3)})`,
    );
  }
  if (segments.length === 0) return String(sorted[0].value * clipVolume);
  // Multiply by base volume.
  return `(${sorted[0].value.toFixed(3)}*between(t,0,${sorted[0].time.toFixed(3)})` +
    `+${segments.join('+')}` +
    `+${sorted[sorted.length - 1].value.toFixed(3)}*between(t,${sorted[sorted.length - 1].time.toFixed(3)},1e9))` +
    `*${clipVolume}`;
}