async function ensureWidevine(components, platform = process.platform) {
    if (!components
        || typeof components.whenReady !== "function"
        || !components.WIDEVINE_CDM_ID) {
        console.warn(
            "[SWAI] This Electron runtime does not provide Widevine component support",
        );
        return { supported: false, ready: false, restartRequired: false };
    }

    const widevineId = components.WIDEVINE_CDM_ID;
    try {
        const results = await components.whenReady([widevineId]);
        const widevine = results.find((result) => result.id === widevineId);
        if (!widevine || !widevine.version) {
            throw new Error("the component updater did not return a Widevine version");
        }

        console.log(
            `[SWAI] Widevine ${widevine.version} component status: ${widevine.status}`,
        );
        return {
            supported: true,
            ready: true,
            // A Linux CDM installed/updated in this process cannot be loaded by
            // the sandbox until the next process. "new" means the component
            // was already current when this process started.
            restartRequired: platform === "linux" && widevine.status === "updated",
            version: widevine.version,
            status: widevine.status,
        };
    } catch (error) {
        console.warn(`[SWAI] Failed to install Widevine: ${error.message}`);
        if (Array.isArray(error.errors)) {
            for (const detail of error.errors) {
                const message = detail?.message
                    || detail?.error
                    || JSON.stringify(detail);
                console.warn(`[SWAI] Widevine component error: ${message}`);
            }
        }
        return {
            supported: true,
            ready: false,
            restartRequired: false,
            error,
        };
    }
}

module.exports = { ensureWidevine };
