use crate::types::{ErrorKind, Value};
use super::stat_helpers::collect_nums;

/// `VAR.S(value1, ...)` — sample variance: Σ(x-mean)²/(n-1).
/// Requires n≥2. Returns `#DIV/0!` if fewer than 2 numeric values.
pub fn var_s_fn(args: &[Value]) -> Value {
    if args.is_empty() {
        return Value::Error(ErrorKind::NA);
    }
    let nums = collect_nums(args);
    sample_variance(&nums)
}

/// Compute sample variance from a slice of f64 values.
pub(crate) fn sample_variance(nums: &[f64]) -> Value {
    let n = nums.len();
    if n < 2 {
        return Value::Error(ErrorKind::DivByZero);
    }
    let mean = nums.iter().sum::<f64>() / n as f64;
    let var = nums.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1) as f64;
    if !var.is_finite() {
        return Value::Error(ErrorKind::Num);
    }
    Value::Number(var)
}

#[cfg(test)]
mod tests;
