export const AUDIO_CONFIG = {
    echoCancellation: true,
    noiseSuppression: true,
    autoGainControl: true
};

export const VAD_CONFIG = {
    threshold: 15,
    debounceTime: 500,
    fftSize: 256
};

export const MEDIA_CONSTRAINTS = {
    video: {
        width: { ideal: 1920, max: 1920 },
        height: { ideal: 1080, max: 1080 },
        frameRate: { ideal: 30, max: 30 }
    },
    audio: AUDIO_CONFIG
};

export const VIDEO_ONLY_CONSTRAINT = {
    video: {
        width: { ideal: 1920, max: 1920 },
        height: { ideal: 1080, max: 1080 },
        frameRate: { ideal: 30, max: 30 }
    },
    audio: false
};

const TARGET_RESOLUTION_BITRATE_MAP = {
    270: 1000000,
    480: 1500000,
    720: 2500000,
    1080: 4000000,
    1440: 6000000
};

export function buildVideoConstraints(savedResolution) {
    if (!savedResolution) {
        return MEDIA_CONSTRAINTS.video;
    }

    return {
        width: { ideal: savedResolution.width, max: savedResolution.width },
        height: { ideal: savedResolution.height, max: savedResolution.height },
        frameRate: { ideal: 30, max: 30 }
    };
}

export function getResolutionLabel(height) {
    if (height >= 1440) {
        return '2K 1440p';
    }
    if (height >= 1080) {
        return '1080p 超清';
    }
    if (height >= 720) {
        return '720p 高清';
    }
    return '480p 流畅';
}

export function getTargetResolutionBitrate(height) {
    return TARGET_RESOLUTION_BITRATE_MAP[height] || 2500000;
}

export function getAdaptiveVideoBitrate(height) {
    const supportedHeights = Object.keys(TARGET_RESOLUTION_BITRATE_MAP).map(Number).sort((a, b) => a - b);
    let maxBitrate = TARGET_RESOLUTION_BITRATE_MAP[1080];

    for (const supportedHeight of supportedHeights) {
        if (height <= supportedHeight) {
            return TARGET_RESOLUTION_BITRATE_MAP[supportedHeight];
        }
        maxBitrate = TARGET_RESOLUTION_BITRATE_MAP[supportedHeight];
    }

    return maxBitrate;
}
