import { EF_INTERACTIVE } from "../../../EF_INTERACTIVE.js";
import { AssetMediaEngine } from "../AssetMediaEngine.js";
import { AssetIdMediaEngine } from "../AssetIdMediaEngine.js";
import { JitMediaEngine } from "../JitMediaEngine.js";
import { Task } from "@lit/task";
const getLatestMediaEngine = async (host, signal) => {
	const mediaEngine = await host.mediaEngineTask.taskComplete;
	signal.throwIfAborted();
	if (!mediaEngine) throw new Error("Media engine is not available");
	return mediaEngine;
};
const getVideoRendition = (mediaEngine) => {
	const videoRendition = mediaEngine.videoRendition;
	if (!videoRendition) throw new Error("Video rendition is not available");
	return videoRendition;
};
/**
* Core logic for creating a MediaEngine with explicit dependencies.
* Pure function that requires all dependencies to be provided.
*/
const createMediaEngine = (host) => {
	const { src, assetId, urlGenerator, apiHost } = host;
	if (assetId !== null && assetId !== void 0 && assetId.trim() !== "") {
		if (!apiHost) return Promise.reject(/* @__PURE__ */ new Error("API host is required for AssetID mode"));
		return AssetIdMediaEngine.fetchByAssetId(host, urlGenerator, assetId, apiHost);
	}
	if (!src || typeof src !== "string" || src.trim() === "") {
		console.error(`Unsupported media source: ${src}, assetId: ${assetId}`);
		return Promise.reject(/* @__PURE__ */ new Error("Unsupported media source"));
	}
	const lowerSrc = src.toLowerCase();
	if (lowerSrc.startsWith("http://") || lowerSrc.startsWith("https://")) {
		const url = urlGenerator.generateManifestUrl(src);
		return JitMediaEngine.fetch(host, urlGenerator, url);
	}
	return AssetMediaEngine.fetch(host, urlGenerator, src);
};
/**
* Handle completion of media engine task - triggers necessary updates.
* Extracted for testability.
*/
const handleMediaEngineComplete = (host) => {
	host.requestUpdate("intrinsicDurationMs");
	host.requestUpdate("ownCurrentTimeMs");
	host.rootTimegroup?.requestUpdate("ownCurrentTimeMs");
	host.rootTimegroup?.requestUpdate("durationMs");
};
const makeMediaEngineTask = (host) => {
	return new Task(host, {
		autoRun: EF_INTERACTIVE,
		args: () => [host.src, host.assetId],
		task: async () => {
			return createMediaEngine(host);
		},
		onComplete: (_value) => {
			handleMediaEngineComplete(host);
		}
	});
};
export { getLatestMediaEngine, getVideoRendition, makeMediaEngineTask };
