import { AlignedLyric, EditTiming } from '../edit2025/types';
import { BeatAlignedLyric, StudioClip } from './types';
import { getLyricsBetween } from './useStudioLyricsEditController';

const CACHE_SIZE = 50;
const CACHE_ENTRIES: [
  [EditTiming, StudioClip[], Record<string, AlignedLyric[]>, number, number],
  BeatAlignedLyric[],
][] = [];
const cachedGetLyricsBetween = (
  ...args: [
    EditTiming,
    StudioClip[],
    Record<string, AlignedLyric[]>,
    number,
    number,
  ]
) => {
  const cachedEntry = CACHE_ENTRIES.find(([cachedArgs]) =>
    cachedArgs.every(
      (a, i) =>
        a === args[i] ||
        (a instanceof Array &&
          args[i] instanceof Array &&
          a.every((e, j) => e === (args[i] as any[])[j]))
    )
  );
  if (cachedEntry) {
    return cachedEntry[1];
  }
  if (CACHE_ENTRIES.length >= CACHE_SIZE) {
    CACHE_ENTRIES.splice(0, CACHE_ENTRIES.length - CACHE_SIZE + 1);
  }
  const result = getLyricsBetween(...args);
  CACHE_ENTRIES.push([args, result]);
  return result;
};

export default cachedGetLyricsBetween;
