// src/composables/useVideoStream.js

/**
 * 将 h264-converter 的 MSE SourceBuffer 做“回放缓冲裁剪”，
 * 防止 buffered 越积越多导致内存上涨。
 *
 * @param {Array<object>} instanceList - 你的 instanceList（每个 index 有 converter）
 * @param {object} videoElementRef     - 你的 videoElement ref 对象（udid->video）
 * @param {import('vue').Ref<Array>} deviceInformationRef - 设备列表（取 udid）
 * @param {number} index
 * @param {number} backBufferSec       - 保留最近多少秒
 * @param {number} intervalMs          - 多久裁剪一次
 */
export function attachTrimmerForIndex(
    instanceList,
    videoElementRef,
    deviceInformationRef,
    index,
    backBufferSec = 10,
    intervalMs = 2000
) {
    const conv = instanceList[index]?.converter;
    if (!conv) return;

    const ensureAttach = () => {
        const ms = conv.mediaSource;
        if (!ms) return false;
        if (ms.readyState !== "open") return false;
        if (!conv.sourceBuffer) return false;
        return true;
    };

    if (conv._trimTimer) {
        clearInterval(conv._trimTimer);
        conv._trimTimer = null;
    }
    if (conv._mseListenersInstalled !== true && conv.mediaSource) {
        conv._mseListenersInstalled = true;
        conv.mediaSource.addEventListener("sourceopen", () => {
            attachTrimmerForIndex(
                instanceList,
                videoElementRef,
                deviceInformationRef,
                index,
                backBufferSec,
                intervalMs
            );
        });
        conv.mediaSource.addEventListener("sourceclose", () => {
            if (conv._trimTimer) {
                clearInterval(conv._trimTimer);
                conv._trimTimer = null;
            }
        });
        conv.mediaSource.addEventListener("error", () => {
            if (conv._trimTimer) {
                clearInterval(conv._trimTimer);
                conv._trimTimer = null;
            }
        });
    }

    if (!ensureAttach()) {
        const waitId = setInterval(() => {
            if (ensureAttach()) {
                clearInterval(waitId);
                attachTrimmerForIndex(
                    instanceList,
                    videoElementRef,
                    deviceInformationRef,
                    index,
                    backBufferSec,
                    intervalMs
                );
            }
        }, 300);
        return;
    }

    conv._trimTimer = setInterval(() => {
        const currentConv = instanceList[index]?.converter;
        const ms = currentConv?.mediaSource;
        const sb = currentConv?.sourceBuffer;
        const udid = deviceInformationRef.value[index]?.udid;
        const video = udid ? videoElementRef.value[udid] : null;

        if (!currentConv || !ms || ms.readyState !== "open" || !sb || !video) return;
        if (sb.updating || video.seeking || video.readyState < 2) return;

        const cur = video.currentTime || 0;
        const trimTo = Math.max(0, cur - backBufferSec);

        try {
            for (let i = 0; i < sb.buffered.length; i++) {
                const start = sb.buffered.start(i);
                const end = sb.buffered.end(i);
                if (end < trimTo - 0.25) {
                    try { sb.remove(0, end); } catch { }
                    break;
                }
            }
        } catch (e) {
            // 忽略一次性错误（例如 SourceBuffer 被移除）
        }
    }, intervalMs);
}
