// Module-level peaks cache. Dedupes in-flight decodes; caches resolved buffers.
// See ADR-002.

import { decodePeaks } from './decodePeaks';

const cache = new Map<string, Float32Array>();
const inflight = new Map<string, Promise<Float32Array>>();

export async function getPeaks(src: string, buckets?: number): Promise<Float32Array> {
  const hit = cache.get(src);
  if (hit) return hit;
  const flying = inflight.get(src);
  if (flying) return flying;
  const promise = decodePeaks(src, buckets).then((peaks) => {
    cache.set(src, peaks);
    return peaks;
  });
  inflight.set(src, promise);
  try {
    return await promise;
  } finally {
    inflight.delete(src);
  }
}

export function setPeaks(src: string, peaks: Float32Array): void {
  cache.set(src, peaks);
}

export function getPeaksFromCache(src: string): Float32Array | undefined {
  return cache.get(src);
}

export function clearPeaksCache(src?: string): void {
  if (src) cache.delete(src);
  else cache.clear();
}
