import { Task } from "@lit/task";
import type { MediaEngine } from "../../../transcoding/types";
import type { EFMedia } from "../../EFMedia";
import { getLatestMediaEngine } from "../tasks/makeMediaEngineTask";

export const makeAudioSegmentFetchTask = (
  host: EFMedia,
): Task<
  readonly [MediaEngine | undefined, number | undefined],
  ArrayBuffer
> => {
  return new Task(host, {
    args: () =>
      [host.mediaEngineTask.value, host.audioSegmentIdTask.value] as const,
    onError: (error) => {
      console.error("audioSegmentFetchTask error", error);
    },
    onComplete: (_value) => {},
    task: async (_, { signal }) => {
      const mediaEngine = await getLatestMediaEngine(host, signal);
      const segmentId = await host.audioSegmentIdTask.taskComplete;
      if (segmentId === undefined) {
        // Provide more context in the error to help with debugging
        const rendition = mediaEngine.audioRendition;
        const debugInfo = {
          hasRendition: !!rendition,
          segmentDurationMs: rendition?.segmentDurationMs,
          segmentDurationsMs: rendition?.segmentDurationsMs?.length || 0,
          desiredSeekTimeMs: host.desiredSeekTimeMs,
          intrinsicDurationMs: host.intrinsicDurationMs,
        };
        throw new Error(
          `Segment ID is not available for audio. Debug info: ${JSON.stringify(debugInfo)}`,
        );
      }

      // SIMPLIFIED: Direct call to mediaEngine - deduplication is built-in
      return mediaEngine.fetchMediaSegment(
        segmentId,
        mediaEngine.getAudioRendition(),
        signal,
      );
    },
  });
};
