import {timeline, type SpeechEvent} from "./script";
import voicevoxManifest from "./voicevox-manifest.json";

type ManifestEntry = {
  id: string;
  character?: string;
  speakerName?: string;
  styleName?: string;
  speakerId?: number;
  file: string;
  durationSeconds: number;
};

const manifestEntries = voicevoxManifest as ManifestEntry[];
const manifestById = new Map(
  manifestEntries.map((entry) => [entry.id, entry])
);

export const PIZZA_KILN_FPS = 30;
export const PIZZA_KILN_GAP_FRAMES = 6;
export const PIZZA_KILN_VIDEO_FRAMES = 154;

export const hasAudioForSpeech = (speech: SpeechEvent) =>
  manifestById.has(speech.id);

export const audioFileForSpeech = (speech: SpeechEvent) =>
  manifestById.get(speech.id)?.file ??
  `audio/pizza-kiln/lines/${speech.id}.wav`;

export const durationForSpeech = (
  speech: SpeechEvent,
  fps = PIZZA_KILN_FPS
) => {
  const entry = manifestById.get(speech.id);
  if (entry && Number.isFinite(entry.durationSeconds)) {
    return Math.max(1, Math.ceil(entry.durationSeconds * fps));
  }

  const estimatedSeconds = Math.max(1.2, speech.text.length * 0.11);
  return Math.ceil(estimatedSeconds * fps);
};

export const totalPizzaKilnDurationInFrames = (fps = PIZZA_KILN_FPS) =>
  durationForSpeech(timeline[0], fps) +
  PIZZA_KILN_GAP_FRAMES +
  PIZZA_KILN_VIDEO_FRAMES +
  PIZZA_KILN_GAP_FRAMES +
  durationForSpeech(timeline[1], fps);
