#[cfg(feature = "python")]
use numpy::{IntoPyArray, PyArray1, PyArrayMethods, PyReadonlyArray1};
#[cfg(feature = "python")]
use pyo3::exceptions::PyValueError;
#[cfg(feature = "python")]
use pyo3::prelude::*;
#[cfg(feature = "python")]
use pyo3::types::PyDict;
#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
use serde::{Deserialize, Serialize};
#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
use wasm_bindgen::prelude::*;

use crate::utilities::data_loader::{source_type, Candles};
use crate::utilities::enums::Kernel;
use crate::utilities::helpers::{
    alloc_with_nan_prefix, detect_best_batch_kernel, detect_best_kernel, init_matrix_prefixes,
    make_uninit_matrix,
};
#[cfg(feature = "python")]
use crate::utilities::kernel_validation::validate_kernel;
#[cfg(not(target_arch = "wasm32"))]
use rayon::prelude::*;
use std::collections::VecDeque;
use std::convert::AsRef;
use std::error::Error;
use std::mem::MaybeUninit;
use thiserror::Error;

#[derive(Debug, Clone)]
pub enum MidpointData<'a> {
    Candles {
        candles: &'a Candles,
        source: &'a str,
    },
    Slice(&'a [f64]),
}

impl<'a> AsRef<[f64]> for MidpointInput<'a> {
    #[inline(always)]
    fn as_ref(&self) -> &[f64] {
        match &self.data {
            MidpointData::Slice(slice) => slice,
            MidpointData::Candles { candles, source } => source_type(candles, source),
        }
    }
}

#[derive(Debug, Clone)]
pub struct MidpointOutput {
    pub values: Vec<f64>,
}

#[derive(Debug, Clone)]
#[cfg_attr(
    all(target_arch = "wasm32", feature = "wasm"),
    derive(Serialize, Deserialize)
)]
pub struct MidpointParams {
    pub period: Option<usize>,
}

impl Default for MidpointParams {
    fn default() -> Self {
        Self { period: Some(14) }
    }
}

#[derive(Debug, Clone)]
pub struct MidpointInput<'a> {
    pub data: MidpointData<'a>,
    pub params: MidpointParams,
}

impl<'a> MidpointInput<'a> {
    #[inline]
    pub fn from_candles(c: &'a Candles, s: &'a str, p: MidpointParams) -> Self {
        Self {
            data: MidpointData::Candles {
                candles: c,
                source: s,
            },
            params: p,
        }
    }
    #[inline]
    pub fn from_slice(sl: &'a [f64], p: MidpointParams) -> Self {
        Self {
            data: MidpointData::Slice(sl),
            params: p,
        }
    }
    #[inline]
    pub fn with_default_candles(c: &'a Candles) -> Self {
        Self::from_candles(c, "close", MidpointParams::default())
    }
    #[inline]
    pub fn get_period(&self) -> usize {
        self.params.period.unwrap_or(14)
    }
}

#[derive(Copy, Clone, Debug)]
pub struct MidpointBuilder {
    period: Option<usize>,
    kernel: Kernel,
}

impl Default for MidpointBuilder {
    fn default() -> Self {
        Self {
            period: None,
            kernel: Kernel::Auto,
        }
    }
}

impl MidpointBuilder {
    #[inline(always)]
    pub fn new() -> Self {
        Self::default()
    }
    #[inline(always)]
    pub fn period(mut self, n: usize) -> Self {
        self.period = Some(n);
        self
    }
    #[inline(always)]
    pub fn kernel(mut self, k: Kernel) -> Self {
        self.kernel = k;
        self
    }
    #[inline(always)]
    pub fn apply(self, c: &Candles) -> Result<MidpointOutput, MidpointError> {
        let p = MidpointParams {
            period: self.period,
        };
        let i = MidpointInput::from_candles(c, "close", p);
        midpoint_with_kernel(&i, self.kernel)
    }
    #[inline(always)]
    pub fn apply_slice(self, d: &[f64]) -> Result<MidpointOutput, MidpointError> {
        let p = MidpointParams {
            period: self.period,
        };
        let i = MidpointInput::from_slice(d, p);
        midpoint_with_kernel(&i, self.kernel)
    }
    #[inline(always)]
    pub fn into_stream(self) -> Result<MidpointStream, MidpointError> {
        let p = MidpointParams {
            period: self.period,
        };
        MidpointStream::try_new(p)
    }
}

#[derive(Debug, Error)]
pub enum MidpointError {
    #[error("midpoint: Empty input data (All values are NaN).")]
    EmptyInputData,
    #[error("midpoint: All values are NaN.")]
    AllValuesNaN,
    #[error("midpoint: Invalid period: period = {period}, data length = {data_len}")]
    InvalidPeriod { period: usize, data_len: usize },
    #[error("midpoint: Not enough valid data: needed = {needed}, valid = {valid}")]
    NotEnoughValidData { needed: usize, valid: usize },
    #[error("midpoint: output length mismatch: expected = {expected}, got = {got}")]
    OutputLengthMismatch { expected: usize, got: usize },
    #[error("midpoint: invalid kernel for batch: {0:?}")]
    InvalidKernelForBatch(Kernel),
    #[error("midpoint: invalid range: start={start}, end={end}, step={step}")]
    InvalidRange {
        start: usize,
        end: usize,
        step: usize,
    },
    #[error("midpoint: invalid input: {0}")]
    InvalidInput(String),
}

#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
impl From<MidpointError> for JsValue {
    fn from(err: MidpointError) -> Self {
        JsValue::from_str(&err.to_string())
    }
}

#[inline]
pub fn midpoint(input: &MidpointInput) -> Result<MidpointOutput, MidpointError> {
    midpoint_with_kernel(input, Kernel::Auto)
}

#[inline(always)]
fn midpoint_prepare<'a>(
    input: &'a MidpointInput,
) -> Result<(&'a [f64], usize, usize, usize), MidpointError> {
    let data: &[f64] = input.as_ref();
    if data.is_empty() {
        return Err(MidpointError::EmptyInputData);
    }

    let first = data
        .iter()
        .position(|x| !x.is_nan())
        .ok_or(MidpointError::AllValuesNaN)?;
    let len = data.len();
    let period = input.get_period();

    if period == 0 || period > len {
        return Err(MidpointError::InvalidPeriod {
            period,
            data_len: len,
        });
    }
    if (len - first) < period {
        return Err(MidpointError::NotEnoughValidData {
            needed: period,
            valid: len - first,
        });
    }

    Ok((data, period, first, len))
}

pub fn midpoint_with_kernel(
    input: &MidpointInput,
    kernel: Kernel,
) -> Result<MidpointOutput, MidpointError> {
    let (data, period, first, len) = midpoint_prepare(input)?;
    let mut out = alloc_with_nan_prefix(len, first + period - 1);

    let chosen = match kernel {
        Kernel::Auto => detect_best_kernel(),
        other => other,
    };

    unsafe {
        match chosen {
            Kernel::Scalar | Kernel::ScalarBatch => midpoint_scalar(data, period, first, &mut out),
            #[cfg(all(feature = "nightly-avx", target_arch = "x86_64"))]
            Kernel::Avx2 | Kernel::Avx2Batch => midpoint_avx2(data, period, first, &mut out),
            #[cfg(all(feature = "nightly-avx", target_arch = "x86_64"))]
            Kernel::Avx512 | Kernel::Avx512Batch => midpoint_avx512(data, period, first, &mut out),
            _ => unreachable!(),
        }
    }

    Ok(MidpointOutput { values: out })
}

#[cfg(not(all(target_arch = "wasm32", feature = "wasm")))]
#[inline]
pub fn midpoint_into(input: &MidpointInput, out: &mut [f64]) -> Result<(), MidpointError> {
    midpoint_into_slice(out, input, Kernel::Auto)
}

#[inline]
pub fn midpoint_into_slice(
    out: &mut [f64],
    input: &MidpointInput,
    kernel: Kernel,
) -> Result<(), MidpointError> {
    let (data, period, first, len) = midpoint_prepare(input)?;

    if out.len() != len {
        return Err(MidpointError::OutputLengthMismatch {
            expected: len,
            got: out.len(),
        });
    }

    for i in 0..(first + period - 1) {
        out[i] = f64::NAN;
    }

    let chosen = match kernel {
        Kernel::Auto => detect_best_kernel(),
        other => other,
    };

    unsafe {
        match chosen {
            Kernel::Scalar | Kernel::ScalarBatch => midpoint_scalar(data, period, first, out),
            #[cfg(all(feature = "nightly-avx", target_arch = "x86_64"))]
            Kernel::Avx2 | Kernel::Avx2Batch => midpoint_avx2(data, period, first, out),
            #[cfg(all(feature = "nightly-avx", target_arch = "x86_64"))]
            Kernel::Avx512 | Kernel::Avx512Batch => midpoint_avx512(data, period, first, out),
            _ => unreachable!(),
        }
    }

    Ok(())
}

#[cfg(all(feature = "nightly-avx", target_arch = "x86_64"))]
#[inline]
pub fn midpoint_avx512(data: &[f64], period: usize, first: usize, out: &mut [f64]) {
    unsafe { midpoint_avx512_long(data, period, first, out) }
}

#[inline]
pub fn midpoint_scalar(data: &[f64], period: usize, first: usize, out: &mut [f64]) {
    for i in (first + period - 1)..data.len() {
        let window = &data[(i + 1 - period)..=i];
        let mut highest = f64::MIN;
        let mut lowest = f64::MAX;
        for &val in window {
            if val > highest {
                highest = val;
            }
            if val < lowest {
                lowest = val;
            }
        }
        out[i] = (highest + lowest) / 2.0;
    }
}

#[cfg(all(feature = "nightly-avx", target_arch = "x86_64"))]
#[inline]
pub fn midpoint_avx2(data: &[f64], period: usize, first: usize, out: &mut [f64]) {
    midpoint_scalar(data, period, first, out)
}

#[cfg(all(feature = "nightly-avx", target_arch = "x86_64"))]
#[inline]
pub fn midpoint_avx512_short(data: &[f64], period: usize, first: usize, out: &mut [f64]) {
    midpoint_scalar(data, period, first, out)
}

#[cfg(all(feature = "nightly-avx", target_arch = "x86_64"))]
#[inline]
pub fn midpoint_avx512_long(data: &[f64], period: usize, first: usize, out: &mut [f64]) {
    midpoint_scalar(data, period, first, out)
}

#[derive(Debug, Clone)]
pub struct MidpointStream {
    period: usize,

    maxdq: VecDeque<(usize, f64)>,

    mindq: VecDeque<(usize, f64)>,

    idx: usize,

    warmup_left: Option<usize>,
}

impl MidpointStream {
    pub fn try_new(params: MidpointParams) -> Result<Self, MidpointError> {
        let period = params.period.unwrap_or(14);
        if period == 0 {
            return Err(MidpointError::InvalidPeriod {
                period,
                data_len: 0,
            });
        }
        Ok(Self {
            period,
            maxdq: VecDeque::with_capacity(period),
            mindq: VecDeque::with_capacity(period),
            idx: 0,
            warmup_left: None,
        })
    }

    #[inline(always)]
    pub fn update(&mut self, value: f64) -> Option<f64> {
        let i = self.idx;
        self.idx = i.wrapping_add(1);

        let start = i.saturating_add(1).saturating_sub(self.period);

        while let Some(&(j, _)) = self.maxdq.front() {
            if j < start {
                self.maxdq.pop_front();
            } else {
                break;
            }
        }
        while let Some(&(j, _)) = self.mindq.front() {
            if j < start {
                self.mindq.pop_front();
            } else {
                break;
            }
        }

        if !value.is_nan() {
            if self.warmup_left.is_none() {
                self.warmup_left = Some(self.period.saturating_sub(1));
            }

            while let Some(&(_, v)) = self.maxdq.back() {
                if v <= value {
                    self.maxdq.pop_back();
                } else {
                    break;
                }
            }
            self.maxdq.push_back((i, value));

            while let Some(&(_, v)) = self.mindq.back() {
                if v >= value {
                    self.mindq.pop_back();
                } else {
                    break;
                }
            }
            self.mindq.push_back((i, value));
        }

        match self.warmup_left {
            None => return None,
            Some(k) if k > 0 => {
                self.warmup_left = Some(k - 1);
                return None;
            }
            _ => {}
        }

        let hi = self.maxdq.front().map(|&(_, v)| v).unwrap_or(f64::MIN);
        let lo = self.mindq.front().map(|&(_, v)| v).unwrap_or(f64::MAX);
        Some(avg2_fast(hi, lo))
    }
}

#[inline(always)]
fn avg2_fast(a: f64, b: f64) -> f64 {
    (a + b).mul_add(0.5, 0.0)
}

#[derive(Clone, Debug)]
pub struct MidpointBatchRange {
    pub period: (usize, usize, usize),
}
impl Default for MidpointBatchRange {
    fn default() -> Self {
        Self {
            period: (14, 263, 1),
        }
    }
}
#[derive(Clone, Debug, Default)]
pub struct MidpointBatchBuilder {
    range: MidpointBatchRange,
    kernel: Kernel,
}
impl MidpointBatchBuilder {
    pub fn new() -> Self {
        Self::default()
    }
    pub fn kernel(mut self, k: Kernel) -> Self {
        self.kernel = k;
        self
    }
    pub fn period_range(mut self, start: usize, end: usize, step: usize) -> Self {
        self.range.period = (start, end, step);
        self
    }
    pub fn period_static(mut self, p: usize) -> Self {
        self.range.period = (p, p, 0);
        self
    }
    pub fn apply_slice(self, data: &[f64]) -> Result<MidpointBatchOutput, MidpointError> {
        midpoint_batch_with_kernel(data, &self.range, self.kernel)
    }
    pub fn with_default_slice(
        data: &[f64],
        k: Kernel,
    ) -> Result<MidpointBatchOutput, MidpointError> {
        MidpointBatchBuilder::new().kernel(k).apply_slice(data)
    }
    pub fn apply_candles(
        self,
        c: &Candles,
        src: &str,
    ) -> Result<MidpointBatchOutput, MidpointError> {
        let slice = source_type(c, src);
        self.apply_slice(slice)
    }
    pub fn with_default_candles(c: &Candles) -> Result<MidpointBatchOutput, MidpointError> {
        MidpointBatchBuilder::new()
            .kernel(Kernel::Auto)
            .apply_candles(c, "close")
    }
}

pub fn midpoint_batch_with_kernel(
    data: &[f64],
    sweep: &MidpointBatchRange,
    k: Kernel,
) -> Result<MidpointBatchOutput, MidpointError> {
    let kernel = match k {
        Kernel::Auto => detect_best_batch_kernel(),
        other if other.is_batch() => other,
        other => return Err(MidpointError::InvalidKernelForBatch(other)),
    };
    let simd = match kernel {
        Kernel::Avx512Batch => Kernel::Avx512,
        Kernel::Avx2Batch => Kernel::Avx2,
        Kernel::ScalarBatch => Kernel::Scalar,
        _ => unreachable!(),
    };
    midpoint_batch_par_slice(data, sweep, simd)
}

#[derive(Clone, Debug)]
pub struct MidpointBatchOutput {
    pub values: Vec<f64>,
    pub combos: Vec<MidpointParams>,
    pub rows: usize,
    pub cols: usize,
}
impl MidpointBatchOutput {
    pub fn row_for_params(&self, p: &MidpointParams) -> Option<usize> {
        self.combos
            .iter()
            .position(|c| c.period.unwrap_or(14) == p.period.unwrap_or(14))
    }
    pub fn values_for(&self, p: &MidpointParams) -> Option<&[f64]> {
        self.row_for_params(p).map(|row| {
            let start = row * self.cols;
            &self.values[start..start + self.cols]
        })
    }
}

#[inline(always)]
fn expand_grid_checked(r: &MidpointBatchRange) -> Result<Vec<MidpointParams>, MidpointError> {
    fn axis_usize((start, end, step): (usize, usize, usize)) -> Result<Vec<usize>, MidpointError> {
        if step == 0 || start == end {
            return Ok(vec![start]);
        }
        let mut out = Vec::new();
        if start < end {
            let mut v = start;
            loop {
                if v > end {
                    break;
                }
                out.push(v);
                match v.checked_add(step) {
                    Some(next) => {
                        if next == v {
                            break;
                        }
                        v = next;
                    }
                    None => break,
                }
            }
        } else {
            let mut v = start;
            loop {
                if v < end {
                    break;
                }
                out.push(v);
                if v == end {
                    break;
                }
                let next = match v.checked_sub(step) {
                    Some(n) => n,
                    None => break,
                };
                if next > v {
                    break;
                }
                v = next;
            }
        }
        if out.is_empty() {
            return Err(MidpointError::InvalidRange { start, end, step });
        }
        Ok(out)
    }
    let periods = axis_usize(r.period)?;
    let mut out = Vec::with_capacity(periods.len());
    for &p in &periods {
        out.push(MidpointParams { period: Some(p) });
    }
    Ok(out)
}

#[inline(always)]
pub fn midpoint_batch_slice(
    data: &[f64],
    sweep: &MidpointBatchRange,
    kern: Kernel,
) -> Result<MidpointBatchOutput, MidpointError> {
    midpoint_batch_inner(data, sweep, kern, false)
}

#[inline(always)]
pub fn midpoint_batch_par_slice(
    data: &[f64],
    sweep: &MidpointBatchRange,
    kern: Kernel,
) -> Result<MidpointBatchOutput, MidpointError> {
    midpoint_batch_inner(data, sweep, kern, true)
}

#[inline(always)]
fn midpoint_batch_inner(
    data: &[f64],
    sweep: &MidpointBatchRange,
    kern: Kernel,
    parallel: bool,
) -> Result<MidpointBatchOutput, MidpointError> {
    if data.is_empty() {
        return Err(MidpointError::EmptyInputData);
    }

    let combos = expand_grid_checked(sweep)?;

    let first = data
        .iter()
        .position(|x| !x.is_nan())
        .ok_or(MidpointError::AllValuesNaN)?;
    let max_p = combos.iter().map(|c| c.period.unwrap()).max().unwrap();
    if data.len() - first < max_p {
        return Err(MidpointError::NotEnoughValidData {
            needed: max_p,
            valid: data.len() - first,
        });
    }

    let rows = combos.len();
    let cols = data.len();

    let mut buf_mu = make_uninit_matrix(rows, cols);
    let warm_prefixes: Vec<usize> = combos
        .iter()
        .map(|c| first + c.period.unwrap() - 1)
        .collect();
    init_matrix_prefixes(&mut buf_mu, cols, &warm_prefixes);

    let mut guard = core::mem::ManuallyDrop::new(buf_mu);
    let out_mu: &mut [MaybeUninit<f64>] =
        unsafe { core::slice::from_raw_parts_mut(guard.as_mut_ptr(), guard.len()) };

    let do_row = |row: usize, row_mu: &mut [MaybeUninit<f64>]| unsafe {
        let period = combos[row].period.unwrap();

        let row_out: &mut [f64] =
            core::slice::from_raw_parts_mut(row_mu.as_mut_ptr() as *mut f64, row_mu.len());

        match kern {
            Kernel::Scalar => midpoint_row_scalar(data, first, period, row_out),
            #[cfg(all(feature = "nightly-avx", target_arch = "x86_64"))]
            Kernel::Avx2 => midpoint_row_avx2(data, first, period, row_out),
            #[cfg(all(feature = "nightly-avx", target_arch = "x86_64"))]
            Kernel::Avx512 => midpoint_row_avx512(data, first, period, row_out),
            _ => unreachable!(),
        }
    };

    if parallel {
        #[cfg(not(target_arch = "wasm32"))]
        {
            out_mu
                .par_chunks_mut(cols)
                .enumerate()
                .for_each(|(row, slice)| do_row(row, slice));
        }
        #[cfg(target_arch = "wasm32")]
        {
            for (row, slice) in out_mu.chunks_mut(cols).enumerate() {
                do_row(row, slice);
            }
        }
    } else {
        for (row, slice) in out_mu.chunks_mut(cols).enumerate() {
            do_row(row, slice);
        }
    }

    let values: Vec<f64> = unsafe {
        Vec::from_raw_parts(
            guard.as_mut_ptr() as *mut f64,
            guard.len(),
            guard.capacity(),
        )
    };

    Ok(MidpointBatchOutput {
        values,
        combos,
        rows,
        cols,
    })
}

#[inline(always)]
unsafe fn midpoint_row_scalar(data: &[f64], first: usize, period: usize, out: &mut [f64]) {
    midpoint_scalar(data, period, first, out)
}
#[cfg(all(feature = "nightly-avx", target_arch = "x86_64"))]
#[inline(always)]
unsafe fn midpoint_row_avx2(data: &[f64], first: usize, period: usize, out: &mut [f64]) {
    midpoint_scalar(data, period, first, out)
}
#[cfg(all(feature = "nightly-avx", target_arch = "x86_64"))]
#[inline(always)]
unsafe fn midpoint_row_avx512(data: &[f64], first: usize, period: usize, out: &mut [f64]) {
    midpoint_scalar(data, period, first, out)
}
#[cfg(all(feature = "nightly-avx", target_arch = "x86_64"))]
#[inline(always)]
unsafe fn midpoint_row_avx512_short(data: &[f64], first: usize, period: usize, out: &mut [f64]) {
    midpoint_scalar(data, period, first, out)
}
#[cfg(all(feature = "nightly-avx", target_arch = "x86_64"))]
#[inline(always)]
unsafe fn midpoint_row_avx512_long(data: &[f64], first: usize, period: usize, out: &mut [f64]) {
    midpoint_scalar(data, period, first, out)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::skip_if_unsupported;
    use crate::utilities::data_loader::read_candles_from_csv;
    #[cfg(feature = "proptest")]
    use proptest::prelude::*;

    fn check_midpoint_partial_params(
        test_name: &str,
        kernel: Kernel,
    ) -> Result<(), Box<dyn Error>> {
        skip_if_unsupported!(kernel, test_name);
        let file_path = "src/data/2018-09-01-2024-Bitfinex_Spot-4h.csv";
        let candles = read_candles_from_csv(file_path)?;
        let default_params = MidpointParams { period: None };
        let input = MidpointInput::from_candles(&candles, "close", default_params);
        let output = midpoint_with_kernel(&input, kernel)?;
        assert_eq!(output.values.len(), candles.close.len());
        Ok(())
    }
    fn check_midpoint_accuracy(test_name: &str, kernel: Kernel) -> Result<(), Box<dyn Error>> {
        skip_if_unsupported!(kernel, test_name);
        let file_path = "src/data/2018-09-01-2024-Bitfinex_Spot-4h.csv";
        let candles = read_candles_from_csv(file_path)?;
        let input = MidpointInput::from_candles(&candles, "close", MidpointParams::default());
        let result = midpoint_with_kernel(&input, kernel)?;
        let expected_last_five = [59578.5, 59578.5, 59578.5, 58886.0, 58886.0];
        let start = result.values.len().saturating_sub(5);
        for (i, &val) in result.values[start..].iter().enumerate() {
            let diff = (val - expected_last_five[i]).abs();
            assert!(
                diff < 1e-1,
                "[{}] MIDPOINT {:?} mismatch at idx {}: got {}, expected {}",
                test_name,
                kernel,
                i,
                val,
                expected_last_five[i]
            );
        }
        Ok(())
    }
    fn check_midpoint_default_candles(
        test_name: &str,
        kernel: Kernel,
    ) -> Result<(), Box<dyn Error>> {
        skip_if_unsupported!(kernel, test_name);
        let file_path = "src/data/2018-09-01-2024-Bitfinex_Spot-4h.csv";
        let candles = read_candles_from_csv(file_path)?;
        let input = MidpointInput::with_default_candles(&candles);
        match input.data {
            MidpointData::Candles { source, .. } => assert_eq!(source, "close"),
            _ => panic!("Expected MidpointData::Candles"),
        }
        let output = midpoint_with_kernel(&input, kernel)?;
        assert_eq!(output.values.len(), candles.close.len());
        Ok(())
    }
    fn check_midpoint_zero_period(test_name: &str, kernel: Kernel) -> Result<(), Box<dyn Error>> {
        skip_if_unsupported!(kernel, test_name);
        let input_data = [10.0, 20.0, 30.0];
        let params = MidpointParams { period: Some(0) };
        let input = MidpointInput::from_slice(&input_data, params);
        let res = midpoint_with_kernel(&input, kernel);
        assert!(
            res.is_err(),
            "[{}] MIDPOINT should fail with zero period",
            test_name
        );
        Ok(())
    }
    fn check_midpoint_period_exceeds_length(
        test_name: &str,
        kernel: Kernel,
    ) -> Result<(), Box<dyn Error>> {
        skip_if_unsupported!(kernel, test_name);
        let data_small = [10.0, 20.0, 30.0];
        let params = MidpointParams { period: Some(10) };
        let input = MidpointInput::from_slice(&data_small, params);
        let res = midpoint_with_kernel(&input, kernel);
        assert!(
            res.is_err(),
            "[{}] MIDPOINT should fail with period exceeding length",
            test_name
        );
        Ok(())
    }
    fn check_midpoint_very_small_dataset(
        test_name: &str,
        kernel: Kernel,
    ) -> Result<(), Box<dyn Error>> {
        skip_if_unsupported!(kernel, test_name);
        let single_point = [42.0];
        let params = MidpointParams { period: Some(9) };
        let input = MidpointInput::from_slice(&single_point, params);
        let res = midpoint_with_kernel(&input, kernel);
        assert!(
            res.is_err(),
            "[{}] MIDPOINT should fail with insufficient data",
            test_name
        );
        Ok(())
    }
    fn check_midpoint_reinput(test_name: &str, kernel: Kernel) -> Result<(), Box<dyn Error>> {
        skip_if_unsupported!(kernel, test_name);
        let file_path = "src/data/2018-09-01-2024-Bitfinex_Spot-4h.csv";
        let candles = read_candles_from_csv(file_path)?;
        let first_params = MidpointParams { period: Some(14) };
        let first_input = MidpointInput::from_candles(&candles, "close", first_params);
        let first_result = midpoint_with_kernel(&first_input, kernel)?;
        let second_params = MidpointParams { period: Some(14) };
        let second_input = MidpointInput::from_slice(&first_result.values, second_params);
        let second_result = midpoint_with_kernel(&second_input, kernel)?;
        assert_eq!(second_result.values.len(), first_result.values.len());
        Ok(())
    }
    fn check_midpoint_nan_handling(test_name: &str, kernel: Kernel) -> Result<(), Box<dyn Error>> {
        skip_if_unsupported!(kernel, test_name);
        let file_path = "src/data/2018-09-01-2024-Bitfinex_Spot-4h.csv";
        let candles = read_candles_from_csv(file_path)?;
        let input = MidpointInput::from_candles(&candles, "close", MidpointParams::default());
        let res = midpoint_with_kernel(&input, kernel)?;
        assert_eq!(res.values.len(), candles.close.len());
        if res.values.len() > 240 {
            for (i, &val) in res.values[240..].iter().enumerate() {
                assert!(
                    !val.is_nan(),
                    "[{}] Found unexpected NaN at out-index {}",
                    test_name,
                    240 + i
                );
            }
        }
        Ok(())
    }
    fn check_midpoint_streaming(test_name: &str, kernel: Kernel) -> Result<(), Box<dyn Error>> {
        skip_if_unsupported!(kernel, test_name);
        let file_path = "src/data/2018-09-01-2024-Bitfinex_Spot-4h.csv";
        let candles = read_candles_from_csv(file_path)?;
        let period = 14;
        let input = MidpointInput::from_candles(
            &candles,
            "close",
            MidpointParams {
                period: Some(period),
            },
        );
        let batch_output = midpoint_with_kernel(&input, kernel)?.values;
        let mut stream = MidpointStream::try_new(MidpointParams {
            period: Some(period),
        })?;
        let mut stream_values = Vec::with_capacity(candles.close.len());
        for &price in &candles.close {
            match stream.update(price) {
                Some(mid_val) => stream_values.push(mid_val),
                None => stream_values.push(f64::NAN),
            }
        }
        assert_eq!(batch_output.len(), stream_values.len());
        for (i, (&b, &s)) in batch_output.iter().zip(stream_values.iter()).enumerate() {
            if b.is_nan() && s.is_nan() {
                continue;
            }
            let diff = (b - s).abs();
            assert!(
                diff < 1e-9,
                "[{}] MIDPOINT streaming f64 mismatch at idx {}: batch={}, stream={}, diff={}",
                test_name,
                i,
                b,
                s,
                diff
            );
        }
        Ok(())
    }

    fn check_midpoint_constant_data(test_name: &str, kernel: Kernel) -> Result<(), Box<dyn Error>> {
        skip_if_unsupported!(kernel, test_name);

        let constant_val = 42.5;
        let data = vec![constant_val; 100];
        let params = MidpointParams { period: Some(10) };
        let input = MidpointInput::from_slice(&data, params);
        let result = midpoint_with_kernel(&input, kernel)?;

        for i in 9..100 {
            assert!(
				(result.values[i] - constant_val).abs() < 1e-10,
				"[{}] Constant data should produce constant midpoint at index {}: expected {}, got {}",
				test_name, i, constant_val, result.values[i]
			);
        }
        Ok(())
    }

    fn check_midpoint_monotonic_increasing(
        test_name: &str,
        kernel: Kernel,
    ) -> Result<(), Box<dyn Error>> {
        skip_if_unsupported!(kernel, test_name);

        let data: Vec<f64> = (0..100).map(|i| i as f64).collect();
        let period = 10;
        let params = MidpointParams {
            period: Some(period),
        };
        let input = MidpointInput::from_slice(&data, params);
        let result = midpoint_with_kernel(&input, kernel)?;

        for i in (period - 1)..data.len() {
            let expected = (data[i + 1 - period] + data[i]) / 2.0;
            assert!(
                (result.values[i] - expected).abs() < 1e-10,
                "[{}] Monotonic increasing midpoint mismatch at index {}: expected {}, got {}",
                test_name,
                i,
                expected,
                result.values[i]
            );
        }
        Ok(())
    }

    fn check_midpoint_monotonic_decreasing(
        test_name: &str,
        kernel: Kernel,
    ) -> Result<(), Box<dyn Error>> {
        skip_if_unsupported!(kernel, test_name);

        let data: Vec<f64> = (0..100).map(|i| 100.0 - i as f64).collect();
        let period = 10;
        let params = MidpointParams {
            period: Some(period),
        };
        let input = MidpointInput::from_slice(&data, params);
        let result = midpoint_with_kernel(&input, kernel)?;

        for i in (period - 1)..data.len() {
            let expected = (data[i] + data[i + 1 - period]) / 2.0;
            assert!(
                (result.values[i] - expected).abs() < 1e-10,
                "[{}] Monotonic decreasing midpoint mismatch at index {}: expected {}, got {}",
                test_name,
                i,
                expected,
                result.values[i]
            );
        }
        Ok(())
    }

    fn check_midpoint_alternating_extremes(
        test_name: &str,
        kernel: Kernel,
    ) -> Result<(), Box<dyn Error>> {
        skip_if_unsupported!(kernel, test_name);

        let mut data = Vec::with_capacity(100);
        for i in 0..100 {
            data.push(if i % 2 == 0 { 100.0 } else { 0.0 });
        }
        let period = 5;
        let params = MidpointParams {
            period: Some(period),
        };
        let input = MidpointInput::from_slice(&data, params);
        let result = midpoint_with_kernel(&input, kernel)?;

        for i in (period - 1)..data.len() {
            assert!(
                (result.values[i] - 50.0).abs() < 1e-10,
                "[{}] Alternating extremes midpoint should be 50 at index {}: got {}",
                test_name,
                i,
                result.values[i]
            );
        }
        Ok(())
    }

    fn check_midpoint_single_spike(test_name: &str, kernel: Kernel) -> Result<(), Box<dyn Error>> {
        skip_if_unsupported!(kernel, test_name);

        let mut data = vec![10.0; 100];
        data[50] = 100.0;

        let period = 5;
        let params = MidpointParams {
            period: Some(period),
        };
        let input = MidpointInput::from_slice(&data, params);
        let result = midpoint_with_kernel(&input, kernel)?;

        for i in (period - 1)..50 {
            assert!(
                (result.values[i] - 10.0).abs() < 1e-10,
                "[{}] Before spike, midpoint should be 10 at index {}: got {}",
                test_name,
                i,
                result.values[i]
            );
        }

        for i in 50..55 {
            let expected = 55.0;
            assert!(
                (result.values[i] - expected).abs() < 1e-10,
                "[{}] During spike window, midpoint should be 55 at index {}: got {}",
                test_name,
                i,
                result.values[i]
            );
        }

        for i in 55..data.len() {
            assert!(
                (result.values[i] - 10.0).abs() < 1e-10,
                "[{}] Well after spike, midpoint should be 10 at index {}: got {}",
                test_name,
                i,
                result.values[i]
            );
        }
        Ok(())
    }

    fn check_midpoint_boundary_values(
        test_name: &str,
        kernel: Kernel,
    ) -> Result<(), Box<dyn Error>> {
        skip_if_unsupported!(kernel, test_name);

        let data = vec![f64::MAX, f64::MIN, 0.0, 1e-300, 1e300];
        let params = MidpointParams { period: Some(2) };
        let input = MidpointInput::from_slice(&data, params.clone());
        let result = midpoint_with_kernel(&input, kernel)?;

        assert!(
            result.values[1].is_finite(),
            "[{}] Result should be finite for extreme values",
            test_name
        );

        let small_data = vec![1e-300, 2e-300, 3e-300, 4e-300, 5e-300];
        let input_small = MidpointInput::from_slice(&small_data, params);
        let result_small = midpoint_with_kernel(&input_small, kernel)?;

        for i in 1..small_data.len() {
            assert!(
                result_small.values[i] > 0.0 && result_small.values[i].is_finite(),
                "[{}] Should handle very small values at index {}",
                test_name,
                i
            );
        }
        Ok(())
    }

    fn check_midpoint_period_one(test_name: &str, kernel: Kernel) -> Result<(), Box<dyn Error>> {
        skip_if_unsupported!(kernel, test_name);

        let data = vec![1.0, 5.0, 3.0, 7.0, 2.0, 9.0, 4.0];
        let params = MidpointParams { period: Some(1) };
        let input = MidpointInput::from_slice(&data, params);
        let result = midpoint_with_kernel(&input, kernel)?;

        for i in 0..data.len() {
            assert!(
                (result.values[i] - data[i]).abs() < 1e-10,
                "[{}] Period=1 should return input value at index {}: expected {}, got {}",
                test_name,
                i,
                data[i],
                result.values[i]
            );
        }
        Ok(())
    }

    fn check_midpoint_all_same_except_one(
        test_name: &str,
        kernel: Kernel,
    ) -> Result<(), Box<dyn Error>> {
        skip_if_unsupported!(kernel, test_name);

        let mut data = vec![50.0; 100];
        data[30] = 150.0;

        let period = 20;
        let params = MidpointParams {
            period: Some(period),
        };
        let input = MidpointInput::from_slice(&data, params);
        let result = midpoint_with_kernel(&input, kernel)?;

        for i in (period - 1)..30 {
            assert!(
                (result.values[i] - 50.0).abs() < 1e-10,
                "[{}] Before outlier window, midpoint should be 50 at index {}: got {}",
                test_name,
                i,
                result.values[i]
            );
        }

        for i in 30..50 {
            let expected = 100.0;
            assert!(
                (result.values[i] - expected).abs() < 1e-10,
                "[{}] With outlier in window, midpoint should be 100 at index {}: got {}",
                test_name,
                i,
                result.values[i]
            );
        }

        for i in 50..data.len() {
            assert!(
                (result.values[i] - 50.0).abs() < 1e-10,
                "[{}] Well after outlier, midpoint should be 50 at index {}: got {}",
                test_name,
                i,
                result.values[i]
            );
        }
        Ok(())
    }

    #[cfg(debug_assertions)]
    fn check_midpoint_no_poison(test_name: &str, kernel: Kernel) -> Result<(), Box<dyn Error>> {
        skip_if_unsupported!(kernel, test_name);

        let file_path = "src/data/2018-09-01-2024-Bitfinex_Spot-4h.csv";
        let candles = read_candles_from_csv(file_path)?;

        let test_params = vec![
            MidpointParams::default(),
            MidpointParams { period: Some(2) },
            MidpointParams { period: Some(5) },
            MidpointParams { period: Some(7) },
            MidpointParams { period: Some(10) },
            MidpointParams { period: Some(20) },
            MidpointParams { period: Some(30) },
            MidpointParams { period: Some(50) },
            MidpointParams { period: Some(100) },
            MidpointParams { period: Some(200) },
        ];

        for (param_idx, params) in test_params.iter().enumerate() {
            let input = MidpointInput::from_candles(&candles, "close", params.clone());
            let output = midpoint_with_kernel(&input, kernel)?;

            for (i, &val) in output.values.iter().enumerate() {
                if val.is_nan() {
                    continue;
                }

                let bits = val.to_bits();

                if bits == 0x11111111_11111111 {
                    panic!(
                        "[{}] Found alloc_with_nan_prefix poison value {} (0x{:016X}) at index {} \
						 with params: period={} (param set {})",
                        test_name,
                        val,
                        bits,
                        i,
                        params.period.unwrap_or(14),
                        param_idx
                    );
                }

                if bits == 0x22222222_22222222 {
                    panic!(
                        "[{}] Found init_matrix_prefixes poison value {} (0x{:016X}) at index {} \
						 with params: period={} (param set {})",
                        test_name,
                        val,
                        bits,
                        i,
                        params.period.unwrap_or(14),
                        param_idx
                    );
                }

                if bits == 0x33333333_33333333 {
                    panic!(
                        "[{}] Found make_uninit_matrix poison value {} (0x{:016X}) at index {} \
						 with params: period={} (param set {})",
                        test_name,
                        val,
                        bits,
                        i,
                        params.period.unwrap_or(14),
                        param_idx
                    );
                }
            }
        }

        Ok(())
    }

    #[cfg(not(debug_assertions))]
    fn check_midpoint_no_poison(_test_name: &str, _kernel: Kernel) -> Result<(), Box<dyn Error>> {
        Ok(())
    }

    #[cfg(feature = "proptest")]
    #[allow(clippy::float_cmp)]
    fn check_midpoint_property(
        test_name: &str,
        kernel: Kernel,
    ) -> Result<(), Box<dyn std::error::Error>> {
        skip_if_unsupported!(kernel, test_name);

        let strat = (1usize..50, 50usize..400, 0usize..9, any::<u64>()).prop_map(
            |(period, len, scenario, seed)| {
                let mut lcg = seed;
                let mut rng = || {
                    lcg = lcg.wrapping_mul(1103515245).wrapping_add(12345);
                    ((lcg / 65536) % 1000000) as f64 / 10000.0 - 50.0
                };

                let data = match scenario {
                    0 => (0..len).map(|_| rng()).collect(),
                    1 => {
                        let val = rng();
                        vec![val; len]
                    }
                    2 => {
                        let start = rng();
                        let step = rng().abs() / 100.0;
                        (0..len).map(|i| start + (i as f64) * step).collect()
                    }
                    3 => {
                        let start = rng();
                        let step = rng().abs() / 100.0;
                        (0..len).map(|i| start - (i as f64) * step).collect()
                    }
                    4 => (0..len)
                        .map(|i| {
                            if i % 2 == 0 {
                                1000.0 + rng()
                            } else {
                                -1000.0 + rng()
                            }
                        })
                        .collect(),
                    5 => {
                        let amplitude = rng().abs() + 10.0;
                        let offset = rng();
                        (0..len)
                            .map(|i| offset + amplitude * (i as f64 * 0.1).sin())
                            .collect()
                    }
                    6 => (0..len).map(|_| rng() * 1e6).collect(),
                    7 => (0..len).map(|_| rng() * 1e-3).collect(),
                    8 => (0..len)
                        .map(|i| {
                            if i % 3 == 0 {
                                rng() * 1e6
                            } else if i % 3 == 1 {
                                rng() * 1e-3
                            } else {
                                rng()
                            }
                        })
                        .collect(),
                    _ => {
                        let amplitude = rng().abs() + 10.0;
                        let period_len = 20;
                        (0..len)
                            .map(|i| {
                                let phase = (i % period_len) as f64 / period_len as f64;
                                if phase < 0.5 {
                                    amplitude * (2.0 * phase)
                                } else {
                                    amplitude * (2.0 - 2.0 * phase)
                                }
                            })
                            .collect()
                    }
                };

                (data, period, scenario)
            },
        );

        proptest::test_runner::TestRunner::default().run(&strat, |(data, period, scenario)| {
            let params = MidpointParams {
                period: Some(period),
            };
            let input = MidpointInput::from_slice(&data, params);

            let result = midpoint_with_kernel(&input, kernel)?;
            let scalar_result = midpoint_with_kernel(&input, Kernel::Scalar)?;

            let tolerance = |expected: f64| -> f64 { (expected.abs() * 1e-12).max(1e-10) };

            prop_assert_eq!(result.values.len(), data.len());

            let first = data.iter().position(|x| !x.is_nan()).unwrap_or(0);
            let warmup_end = first + period - 1;

            for i in 0..warmup_end.min(result.values.len()) {
                prop_assert!(
                    result.values[i].is_nan(),
                    "Expected NaN at index {} during warmup (warmup_end={})",
                    i,
                    warmup_end
                );
            }

            for i in warmup_end..data.len() {
                let window = &data[(i + 1 - period)..=i];
                let mut highest = f64::MIN;
                let mut lowest = f64::MAX;

                for &val in window {
                    if val > highest {
                        highest = val;
                    }
                    if val < lowest {
                        lowest = val;
                    }
                }

                let expected = (highest + lowest) / 2.0;
                let actual = result.values[i];
                let tol = tolerance(expected);

                prop_assert!(
                    (actual - expected).abs() < tol,
                    "Mathematical accuracy failed at index {}: expected {}, got {}, tolerance {}",
                    i,
                    expected,
                    actual,
                    tol
                );
            }

            for i in 0..result.values.len() {
                let kernel_val = result.values[i];
                let scalar_val = scalar_result.values[i];

                if kernel_val.is_nan() && scalar_val.is_nan() {
                    continue;
                }

                let tol = tolerance(scalar_val);
                prop_assert!(
                    (kernel_val - scalar_val).abs() < tol,
                    "Kernel consistency failed at index {}: kernel={}, scalar={}, tolerance={}",
                    i,
                    kernel_val,
                    scalar_val,
                    tol
                );
            }

            if period == 1 {
                for i in first..data.len() {
                    let tol = tolerance(data[i]);
                    prop_assert!(
                        (result.values[i] - data[i]).abs() < tol,
                        "Period=1 should equal input at index {}: {} vs {}, tolerance {}",
                        i,
                        result.values[i],
                        data[i],
                        tol
                    );
                }
            }

            if !data.is_empty() {
                let first_val = data[first];
                let val_tol = tolerance(first_val);
                if data.windows(2).all(|w| (w[0] - w[1]).abs() < val_tol) {
                    for i in warmup_end..data.len() {
                        prop_assert!(
                            (result.values[i] - first_val).abs() < val_tol,
                            "Constant data should produce constant output at index {}",
                            i
                        );
                    }
                }
            }

            for i in warmup_end..data.len() {
                let window = &data[(i + 1 - period)..=i];
                if !window.is_empty() {
                    let window_val = window[0];
                    let win_tol = tolerance(window_val);
                    if window.windows(2).all(|w| (w[0] - w[1]).abs() < win_tol) {
                        prop_assert!(
                            (result.values[i] - window_val).abs() < win_tol,
                            "Window with identical values should produce that value at index {}",
                            i
                        );
                    }
                }
            }

            if scenario == 2 || scenario == 3 {
                for i in warmup_end..data.len() {
                    let window_start = data[i + 1 - period];
                    let window_end = data[i];
                    let expected_midpoint = (window_start + window_end) / 2.0;
                    let tol = tolerance(expected_midpoint);

                    prop_assert!(
							(result.values[i] - expected_midpoint).abs() < tol,
							"Monotonic data midpoint mismatch at index {}: expected {}, got {}, tolerance {}",
							i, expected_midpoint, result.values[i], tol
						);
                }
            }

            #[cfg(debug_assertions)]
            {
                for (i, &val) in result.values.iter().enumerate() {
                    if val.is_nan() {
                        continue;
                    }

                    let bits = val.to_bits();
                    prop_assert!(
                        bits != 0x11111111_11111111
                            && bits != 0x22222222_22222222
                            && bits != 0x33333333_33333333,
                        "Found poison value at index {}: {} (0x{:016X})",
                        i,
                        val,
                        bits
                    );
                }
            }

            Ok(())
        })?;

        Ok(())
    }

    macro_rules! generate_all_midpoint_tests {
        ($($test_fn:ident),*) => {
            paste::paste! {
                $( #[test] fn [<$test_fn _scalar_f64>]() { let _ = $test_fn(stringify!([<$test_fn _scalar_f64>]), Kernel::Scalar); } )*
                #[cfg(all(feature = "nightly-avx", target_arch = "x86_64"))]
                $( #[test] fn [<$test_fn _avx2_f64>]() { let _ = $test_fn(stringify!([<$test_fn _avx2_f64>]), Kernel::Avx2); }
                   #[test] fn [<$test_fn _avx512_f64>]() { let _ = $test_fn(stringify!([<$test_fn _avx512_f64>]), Kernel::Avx512); }
                )*
            }
        }
    }
    generate_all_midpoint_tests!(
        check_midpoint_partial_params,
        check_midpoint_accuracy,
        check_midpoint_default_candles,
        check_midpoint_zero_period,
        check_midpoint_period_exceeds_length,
        check_midpoint_very_small_dataset,
        check_midpoint_reinput,
        check_midpoint_nan_handling,
        check_midpoint_streaming,
        check_midpoint_no_poison,
        check_midpoint_constant_data,
        check_midpoint_monotonic_increasing,
        check_midpoint_monotonic_decreasing,
        check_midpoint_alternating_extremes,
        check_midpoint_single_spike,
        check_midpoint_boundary_values,
        check_midpoint_period_one,
        check_midpoint_all_same_except_one
    );

    #[cfg(feature = "proptest")]
    generate_all_midpoint_tests!(check_midpoint_property);

    fn check_batch_default_row(test: &str, kernel: Kernel) -> Result<(), Box<dyn Error>> {
        skip_if_unsupported!(kernel, test);
        let file = "src/data/2018-09-01-2024-Bitfinex_Spot-4h.csv";
        let c = read_candles_from_csv(file)?;
        let output = MidpointBatchBuilder::new()
            .kernel(kernel)
            .apply_candles(&c, "close")?;
        let def = MidpointParams::default();
        let row = output.values_for(&def).expect("default row missing");
        assert_eq!(row.len(), c.close.len());
        let expected = [59578.5, 59578.5, 59578.5, 58886.0, 58886.0];
        let start = row.len() - 5;
        for (i, &v) in row[start..].iter().enumerate() {
            assert!(
                (v - expected[i]).abs() < 1e-1,
                "[{test}] default-row mismatch at idx {i}: {v} vs {expected:?}"
            );
        }
        Ok(())
    }

    fn check_batch_multiple_periods(test: &str, kernel: Kernel) -> Result<(), Box<dyn Error>> {
        skip_if_unsupported!(kernel, test);
        let data: Vec<f64> = (0..100).map(|i| i as f64).collect();

        let output = MidpointBatchBuilder::new()
            .kernel(kernel)
            .period_range(5, 15, 5)
            .apply_slice(&data)?;

        assert_eq!(output.rows, 3);
        assert_eq!(output.cols, 100);
        assert_eq!(output.combos.len(), 3);

        let periods = [5, 10, 15];
        for (row_idx, &period) in periods.iter().enumerate() {
            let row = output
                .values_for(&MidpointParams {
                    period: Some(period),
                })
                .expect(&format!("Missing row for period {}", period));

            for i in 0..(period - 1) {
                assert!(
                    row[i].is_nan(),
                    "[{}] Expected NaN at index {} for period {}",
                    test,
                    i,
                    period
                );
            }

            for i in (period - 1)..100 {
                let expected = (data[i + 1 - period] + data[i]) / 2.0;
                assert!(
                    (row[i] - expected).abs() < 1e-10,
                    "[{}] Period {} mismatch at index {}: expected {}, got {}",
                    test,
                    period,
                    i,
                    expected,
                    row[i]
                );
            }
        }
        Ok(())
    }

    fn check_batch_edge_cases(test: &str, kernel: Kernel) -> Result<(), Box<dyn Error>> {
        skip_if_unsupported!(kernel, test);

        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let output = MidpointBatchBuilder::new()
            .kernel(kernel)
            .period_range(3, 5, 10)
            .apply_slice(&data)?;

        assert_eq!(
            output.rows, 1,
            "[{}] Step > range should give single row",
            test
        );
        assert_eq!(output.combos[0].period, Some(3));

        let output2 = MidpointBatchBuilder::new()
            .kernel(kernel)
            .period_static(3)
            .apply_slice(&data)?;

        assert_eq!(
            output2.rows, 1,
            "[{}] Static period should give single row",
            test
        );
        assert_eq!(output2.combos[0].period, Some(3));

        let empty_data: Vec<f64> = vec![];
        let result = MidpointBatchBuilder::new()
            .kernel(kernel)
            .period_static(3)
            .apply_slice(&empty_data);

        assert!(result.is_err(), "[{}] Empty data should fail", test);

        Ok(())
    }

    #[cfg(debug_assertions)]
    fn check_batch_no_poison(test: &str, kernel: Kernel) -> Result<(), Box<dyn Error>> {
        skip_if_unsupported!(kernel, test);

        let file = "src/data/2018-09-01-2024-Bitfinex_Spot-4h.csv";
        let c = read_candles_from_csv(file)?;

        let test_configs = vec![
            (2, 10, 2),
            (5, 25, 5),
            (30, 60, 15),
            (2, 5, 1),
            (10, 20, 2),
            (50, 100, 10),
            (14, 14, 0),
            (3, 7, 1),
        ];

        for (cfg_idx, &(period_start, period_end, period_step)) in test_configs.iter().enumerate() {
            let output = MidpointBatchBuilder::new()
                .kernel(kernel)
                .period_range(period_start, period_end, period_step)
                .apply_candles(&c, "close")?;

            for (idx, &val) in output.values.iter().enumerate() {
                if val.is_nan() {
                    continue;
                }

                let bits = val.to_bits();
                let row = idx / output.cols;
                let col = idx % output.cols;
                let combo = &output.combos[row];

                if bits == 0x11111111_11111111 {
                    panic!(
                        "[{}] Config {}: Found alloc_with_nan_prefix poison value {} (0x{:016X}) \
						 at row {} col {} (flat index {}) with params: period={}",
                        test,
                        cfg_idx,
                        val,
                        bits,
                        row,
                        col,
                        idx,
                        combo.period.unwrap_or(14)
                    );
                }

                if bits == 0x22222222_22222222 {
                    panic!(
                        "[{}] Config {}: Found init_matrix_prefixes poison value {} (0x{:016X}) \
						 at row {} col {} (flat index {}) with params: period={}",
                        test,
                        cfg_idx,
                        val,
                        bits,
                        row,
                        col,
                        idx,
                        combo.period.unwrap_or(14)
                    );
                }

                if bits == 0x33333333_33333333 {
                    panic!(
                        "[{}] Config {}: Found make_uninit_matrix poison value {} (0x{:016X}) \
						 at row {} col {} (flat index {}) with params: period={}",
                        test,
                        cfg_idx,
                        val,
                        bits,
                        row,
                        col,
                        idx,
                        combo.period.unwrap_or(14)
                    );
                }
            }
        }

        Ok(())
    }

    #[cfg(not(debug_assertions))]
    fn check_batch_no_poison(_test: &str, _kernel: Kernel) -> Result<(), Box<dyn Error>> {
        Ok(())
    }
    macro_rules! gen_batch_tests {
        ($fn_name:ident) => {
            paste::paste! {
                #[test] fn [<$fn_name _scalar>]()      { let _ = $fn_name(stringify!([<$fn_name _scalar>]), Kernel::ScalarBatch); }
                #[cfg(all(feature = "nightly-avx", target_arch = "x86_64"))]
                #[test] fn [<$fn_name _avx2>]()        { let _ = $fn_name(stringify!([<$fn_name _avx2>]), Kernel::Avx2Batch); }
                #[cfg(all(feature = "nightly-avx", target_arch = "x86_64"))]
                #[test] fn [<$fn_name _avx512>]()      { let _ = $fn_name(stringify!([<$fn_name _avx512>]), Kernel::Avx512Batch); }
                #[test] fn [<$fn_name _auto_detect>]() { let _ = $fn_name(stringify!([<$fn_name _auto_detect>]), Kernel::Auto); }
            }
        };
    }
    gen_batch_tests!(check_batch_default_row);
    gen_batch_tests!(check_batch_no_poison);
    gen_batch_tests!(check_batch_multiple_periods);
    gen_batch_tests!(check_batch_edge_cases);

    #[test]
    #[cfg(not(all(target_arch = "wasm32", feature = "wasm")))]
    fn test_midpoint_into_matches_api() -> Result<(), Box<dyn Error>> {
        let len = 512usize;
        let mut data = vec![0.0f64; len];

        data[0] = f64::NAN;
        data[1] = f64::NAN;
        data[2] = f64::NAN;
        for i in 3..len {
            let x = i as f64;

            data[i] = 100.0 + 0.05 * x + (0.01 * x).sin() * 2.0;
        }

        let input = MidpointInput::from_slice(&data, MidpointParams::default());

        let baseline = midpoint(&input)?.values;

        let mut out = vec![0.0f64; len];
        midpoint_into(&input, &mut out)?;

        assert_eq!(baseline.len(), out.len());

        #[inline]
        fn eq_or_both_nan(a: f64, b: f64) -> bool {
            (a.is_nan() && b.is_nan()) || (a - b).abs() <= 1e-12
        }

        for (i, (&a, &b)) in baseline.iter().zip(out.iter()).enumerate() {
            assert!(
                eq_or_both_nan(a, b),
                "mismatch at {}: baseline={} into={}",
                i,
                a,
                b
            );
        }

        Ok(())
    }
}

#[inline(always)]
pub fn midpoint_batch_inner_into(
    data: &[f64],
    sweep: &MidpointBatchRange,
    kern: Kernel,
    parallel: bool,
    out: &mut [f64],
) -> Result<Vec<MidpointParams>, MidpointError> {
    if data.is_empty() {
        return Err(MidpointError::EmptyInputData);
    }

    let combos = expand_grid_checked(sweep)?;

    let first = data
        .iter()
        .position(|x| !x.is_nan())
        .ok_or(MidpointError::AllValuesNaN)?;
    let max_p = combos.iter().map(|c| c.period.unwrap()).max().unwrap();
    if data.len() - first < max_p {
        return Err(MidpointError::NotEnoughValidData {
            needed: max_p,
            valid: data.len() - first,
        });
    }

    let rows = combos.len();
    let cols = data.len();
    let _total = rows.checked_mul(cols).ok_or_else(|| {
        MidpointError::InvalidInput("rows*cols overflow in midpoint_batch_inner".into())
    })?;
    let expected = rows.checked_mul(cols).ok_or_else(|| {
        MidpointError::InvalidInput("rows*cols overflow in midpoint_batch_inner_into".into())
    })?;
    if out.len() != expected {
        return Err(MidpointError::OutputLengthMismatch {
            expected,
            got: out.len(),
        });
    }

    let out_mu: &mut [MaybeUninit<f64>] = unsafe {
        core::slice::from_raw_parts_mut(out.as_mut_ptr() as *mut MaybeUninit<f64>, out.len())
    };
    let warm_prefixes: Vec<usize> = combos
        .iter()
        .map(|c| first + c.period.unwrap() - 1)
        .collect();
    init_matrix_prefixes(out_mu, cols, &warm_prefixes);

    let do_row = |row: usize, row_mu: &mut [MaybeUninit<f64>]| unsafe {
        let period = combos[row].period.unwrap();
        let row_out: &mut [f64] =
            core::slice::from_raw_parts_mut(row_mu.as_mut_ptr() as *mut f64, row_mu.len());
        match kern {
            Kernel::Scalar => midpoint_row_scalar(data, first, period, row_out),
            #[cfg(all(feature = "nightly-avx", target_arch = "x86_64"))]
            Kernel::Avx2 => midpoint_row_avx2(data, first, period, row_out),
            #[cfg(all(feature = "nightly-avx", target_arch = "x86_64"))]
            Kernel::Avx512 => midpoint_row_avx512(data, first, period, row_out),
            _ => unreachable!(),
        }
    };

    if parallel {
        #[cfg(not(target_arch = "wasm32"))]
        {
            out_mu
                .par_chunks_mut(cols)
                .enumerate()
                .for_each(|(row, slice)| do_row(row, slice));
        }
        #[cfg(target_arch = "wasm32")]
        {
            for (row, slice) in out_mu.chunks_mut(cols).enumerate() {
                do_row(row, slice);
            }
        }
    } else {
        for (row, slice) in out_mu.chunks_mut(cols).enumerate() {
            do_row(row, slice);
        }
    }

    Ok(combos)
}

#[cfg(feature = "python")]
#[pyfunction(name = "midpoint")]
#[pyo3(signature = (data, period=None, kernel=None))]
pub fn midpoint_py<'py>(
    py: Python<'py>,
    data: PyReadonlyArray1<'py, f64>,
    period: Option<usize>,
    kernel: Option<&str>,
) -> PyResult<Bound<'py, PyArray1<f64>>> {
    use numpy::{IntoPyArray, PyArrayMethods};

    let slice_in = data.as_slice()?;
    let kern = validate_kernel(kernel, false)?;

    let params = MidpointParams { period };
    let input = MidpointInput::from_slice(slice_in, params);

    let result_vec: Vec<f64> = py
        .allow_threads(|| midpoint_with_kernel(&input, kern).map(|o| o.values))
        .map_err(|e| PyValueError::new_err(e.to_string()))?;

    Ok(result_vec.into_pyarray(py))
}

#[cfg(feature = "python")]
#[pyclass(name = "MidpointStream")]
pub struct MidpointStreamPy {
    stream: MidpointStream,
}

#[cfg(feature = "python")]
#[pymethods]
impl MidpointStreamPy {
    #[new]
    fn new(period: Option<usize>) -> PyResult<Self> {
        let params = MidpointParams { period };
        let stream =
            MidpointStream::try_new(params).map_err(|e| PyValueError::new_err(e.to_string()))?;
        Ok(MidpointStreamPy { stream })
    }

    fn update(&mut self, value: f64) -> Option<f64> {
        self.stream.update(value)
    }
}

#[cfg(feature = "python")]
#[pyfunction(name = "midpoint_batch")]
#[pyo3(signature = (data, period_range, kernel=None))]
pub fn midpoint_batch_py<'py>(
    py: Python<'py>,
    data: PyReadonlyArray1<'py, f64>,
    period_range: (usize, usize, usize),
    kernel: Option<&str>,
) -> PyResult<Bound<'py, PyDict>> {
    use numpy::{IntoPyArray, PyArray1, PyArrayMethods};

    let slice_in = data.as_slice()?;
    let kern = validate_kernel(kernel, true)?;

    let sweep = MidpointBatchRange {
        period: period_range,
    };

    let combos = expand_grid_checked(&sweep).map_err(|e| PyValueError::new_err(e.to_string()))?;
    let rows = combos.len();
    let cols = slice_in.len();
    let expected = rows
        .checked_mul(cols)
        .ok_or_else(|| PyValueError::new_err("rows*cols overflow"))?;

    let out_arr = unsafe { PyArray1::<f64>::new(py, [expected], false) };
    let slice_out = unsafe { out_arr.as_slice_mut()? };

    let combos = py
        .allow_threads(|| {
            let kernel = match kern {
                Kernel::Auto => detect_best_batch_kernel(),
                k => k,
            };
            let simd = match kernel {
                Kernel::Avx512Batch => Kernel::Avx512,
                Kernel::Avx2Batch => Kernel::Avx2,
                Kernel::ScalarBatch => Kernel::Scalar,
                _ => unreachable!(),
            };
            midpoint_batch_inner_into(slice_in, &sweep, simd, true, slice_out)
        })
        .map_err(|e| PyValueError::new_err(e.to_string()))?;

    let dict = PyDict::new(py);
    dict.set_item("values", out_arr.reshape((rows, cols))?)?;
    dict.set_item(
        "periods",
        combos
            .iter()
            .map(|p| p.period.unwrap() as u64)
            .collect::<Vec<_>>()
            .into_pyarray(py),
    )?;

    Ok(dict)
}

#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
#[wasm_bindgen]
pub fn midpoint_js(data: &[f64], period: usize) -> Result<Vec<f64>, JsValue> {
    let params = MidpointParams {
        period: Some(period),
    };
    let input = MidpointInput::from_slice(data, params);

    let mut output = vec![0.0; data.len()];
    midpoint_into_slice(&mut output, &input, Kernel::Auto)
        .map_err(|e| JsValue::from_str(&e.to_string()))?;

    Ok(output)
}

#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
#[wasm_bindgen]
pub fn midpoint_alloc(len: usize) -> *mut f64 {
    let mut vec = Vec::<f64>::with_capacity(len);
    let ptr = vec.as_mut_ptr();
    std::mem::forget(vec);
    ptr
}

#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
#[wasm_bindgen]
pub fn midpoint_free(ptr: *mut f64, len: usize) {
    if !ptr.is_null() {
        unsafe {
            let _ = Vec::from_raw_parts(ptr, len, len);
        }
    }
}

#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
#[wasm_bindgen]
pub fn midpoint_into(
    in_ptr: *const f64,
    out_ptr: *mut f64,
    len: usize,
    period: usize,
) -> Result<(), JsValue> {
    if in_ptr.is_null() || out_ptr.is_null() {
        return Err(JsValue::from_str("Null pointer provided"));
    }

    unsafe {
        let data = std::slice::from_raw_parts(in_ptr, len);
        let params = MidpointParams {
            period: Some(period),
        };
        let input = MidpointInput::from_slice(data, params);

        if in_ptr == out_ptr {
            let mut temp = vec![0.0; len];
            midpoint_into_slice(&mut temp, &input, Kernel::Auto)
                .map_err(|e| JsValue::from_str(&e.to_string()))?;
            let out = std::slice::from_raw_parts_mut(out_ptr, len);
            out.copy_from_slice(&temp);
        } else {
            let out = std::slice::from_raw_parts_mut(out_ptr, len);
            midpoint_into_slice(out, &input, Kernel::Auto)
                .map_err(|e| JsValue::from_str(&e.to_string()))?;
        }
        Ok(())
    }
}

#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
#[wasm_bindgen]
pub fn midpoint_batch_into(
    in_ptr: *const f64,
    out_ptr: *mut f64,
    len: usize,
    period_start: usize,
    period_end: usize,
    period_step: usize,
) -> Result<usize, JsValue> {
    if in_ptr.is_null() || out_ptr.is_null() {
        return Err(JsValue::from_str(
            "null pointer passed to midpoint_batch_into",
        ));
    }

    unsafe {
        let data = std::slice::from_raw_parts(in_ptr, len);

        let sweep = MidpointBatchRange {
            period: (period_start, period_end, period_step),
        };

        let combos = expand_grid_checked(&sweep).map_err(|e| JsValue::from_str(&e.to_string()))?;
        let rows = combos.len();
        let cols = len;
        let expected = rows
            .checked_mul(cols)
            .ok_or_else(|| JsValue::from_str("rows*cols overflow in midpoint_batch_into"))?;

        let out = std::slice::from_raw_parts_mut(out_ptr, expected);

        midpoint_batch_inner_into(data, &sweep, detect_best_kernel(), false, out)
            .map_err(|e| JsValue::from_str(&e.to_string()))?;

        Ok(rows)
    }
}

#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
#[derive(Serialize, Deserialize)]
pub struct MidpointBatchConfig {
    pub period_range: (usize, usize, usize),
}

#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
#[derive(Serialize, Deserialize)]
pub struct MidpointBatchJsOutput {
    pub values: Vec<f64>,
    pub combos: Vec<MidpointParams>,
    pub rows: usize,
    pub cols: usize,
}

#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
#[wasm_bindgen(js_name = midpoint_batch)]
pub fn midpoint_batch_js(data: &[f64], config: JsValue) -> Result<JsValue, JsValue> {
    let config: MidpointBatchConfig = serde_wasm_bindgen::from_value(config)
        .map_err(|e| JsValue::from_str(&format!("Invalid config: {}", e)))?;

    let sweep = MidpointBatchRange {
        period: config.period_range,
    };

    let result = midpoint_batch_with_kernel(data, &sweep, Kernel::Auto)
        .map_err(|e| JsValue::from_str(&e.to_string()))?;

    let output = MidpointBatchJsOutput {
        values: result.values,
        combos: result.combos,
        rows: result.rows,
        cols: result.cols,
    };

    serde_wasm_bindgen::to_value(&output).map_err(|e| JsValue::from_str(&e.to_string()))
}
