/// Diagnostics returned by render downmix helpers.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct RenderDownmixStats {
    /// Peak absolute sample magnitude after i16 conversion.
    pub peak_i16: i16,
    /// Samples clipped while applying output gain.
    pub clipped_samples: u64,
}

/// Downmix interleaved stereo f32 samples into mono i16 samples.
///
/// The helper is allocation-free and safe for realtime render callbacks.
/// If the stereo source is shorter than expected, the remainder of `out`
/// is filled with silence.
pub(crate) fn downmix_stereo_f32_to_mono_i16(
    stereo: &[f32],
    out: &mut [i16],
    gain: f32,
    muted: bool,
) -> RenderDownmixStats {
    if muted {
        out.fill(0);
        return RenderDownmixStats::default();
    }

    let available_frames = stereo.len() / 2;
    if available_frames < out.len() {
        out.fill(0);
    }

    let mut peak = 0_u16;
    let mut clipped_samples = 0_u64;
    for (dst, lr) in out.iter_mut().zip(stereo.chunks_exact(2)) {
        let mono = (lr[0] + lr[1]) * 0.5 * gain;
        let clamped = mono.clamp(-1.0, 1.0);
        if (mono - clamped).abs() > f32::EPSILON {
            clipped_samples = clipped_samples.saturating_add(1);
        }
        let sample = (clamped * i16::MAX as f32) as i16;
        *dst = sample;
        peak = peak.max(sample.unsigned_abs());
    }

    RenderDownmixStats {
        peak_i16: peak.min(i16::MAX as u16) as i16,
        clipped_samples,
    }
}

/// Downmix interleaved stereo f32 samples into mono f32 samples.
///
/// Used for software-AEC render references and debug WAV taps.
#[cfg(any(target_os = "ios", test))]
pub(crate) fn downmix_stereo_f32_to_mono_f32(stereo: &[f32], out: &mut [f32]) {
    let available_frames = stereo.len() / 2;
    if available_frames < out.len() {
        out.fill(0.0);
    }

    for (dst, lr) in out.iter_mut().zip(stereo.chunks_exact(2)) {
        *dst = (lr[0] + lr[1]) * 0.5;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn downmix_i16_applies_gain_and_reports_clipping() {
        let stereo = [1.0_f32, 1.0, 0.25, -0.25, -2.0, -2.0];
        let mut out = [0_i16; 3];

        let stats = downmix_stereo_f32_to_mono_i16(&stereo, &mut out, 2.0, false);

        assert_eq!(out[0], i16::MAX);
        assert_eq!(out[1], 0);
        assert_eq!(out[2], -i16::MAX);
        assert_eq!(stats.peak_i16, i16::MAX);
        assert_eq!(stats.clipped_samples, 2);
    }

    #[test]
    fn downmix_i16_mutes_output() {
        let stereo = [1.0_f32, 1.0, -1.0, -1.0];
        let mut out = [123_i16; 2];

        let stats = downmix_stereo_f32_to_mono_i16(&stereo, &mut out, 1.0, true);

        assert_eq!(out, [0, 0]);
        assert_eq!(stats, RenderDownmixStats::default());
    }

    #[test]
    fn downmix_f32_fills_missing_tail_with_silence() {
        let stereo = [1.0_f32, -1.0];
        let mut out = [9.0_f32; 2];

        downmix_stereo_f32_to_mono_f32(&stereo, &mut out);

        assert_eq!(out, [0.0, 0.0]);
    }
}
