import { EF_RENDERING } from "../../../EF_RENDERING.js";
import { manageMediaBuffer } from "../shared/BufferUtils.js";
import { Task } from "@lit/task";
/**
* Scrub video buffer task - aggressively preloads the ENTIRE scrub track
* Unlike main video buffering, this loads the full duration with higher concurrency
* for instant visual feedback during seeking
*/
const makeScrubVideoBufferTask = (host) => {
	let currentState = {
		currentSeekTimeMs: 0,
		requestedSegments: /* @__PURE__ */ new Set(),
		activeRequests: /* @__PURE__ */ new Set(),
		requestQueue: []
	};
	return new Task(host, {
		autoRun: !EF_RENDERING(),
		args: () => [host.mediaEngineTask.value],
		onError: (error) => {
			console.error("scrubVideoBufferTask error", error);
		},
		onComplete: (value) => {
			currentState = value;
		},
		task: async ([mediaEngine], { signal }) => {
			if (EF_RENDERING()) return currentState;
			if (!host.enableVideoBuffering) return currentState;
			if (!mediaEngine) return currentState;
			const scrubRendition = mediaEngine.getScrubVideoRendition();
			if (!scrubRendition) return currentState;
			const scrubRenditionWithSrc = {
				...scrubRendition,
				src: mediaEngine.src
			};
			try {
				try {
					await mediaEngine.fetchInitSegment(scrubRenditionWithSrc, signal);
				} catch (error) {
					console.warn("ScrubBuffer: Failed to cache scrub init segment:", error);
				}
				const newState = await manageMediaBuffer(0, {
					bufferDurationMs: mediaEngine.durationMs,
					maxParallelFetches: 10,
					enableBuffering: true,
					enableContinuousBuffering: true
				}, currentState, mediaEngine.durationMs, signal, {
					computeSegmentId: async (timeMs, rendition) => {
						return mediaEngine.computeSegmentId(timeMs, rendition);
					},
					prefetchSegment: async (segmentId, rendition) => {
						await mediaEngine.fetchMediaSegment(segmentId, rendition);
					},
					isSegmentCached: (segmentId, rendition) => {
						return mediaEngine.isSegmentCached(segmentId, rendition);
					},
					getRendition: async () => scrubRenditionWithSrc,
					logError: (message, error) => {
						console.warn(`ScrubBuffer: ${message}`, error);
					}
				});
				return newState;
			} catch (error) {
				if (signal.aborted) return currentState;
				console.warn("ScrubBuffer failed:", error);
				return currentState;
			}
		}
	});
};
export { makeScrubVideoBufferTask };
