"""Array validation and NaN handling."""

from __future__ import annotations

import numpy as np
from numpy.typing import NDArray


def ensure_float64_1d(arr: NDArray[np.float64] | list[float]) -> NDArray[np.float64]:
    """Ensure 1D float64 array; copy if needed."""
    a = np.asarray(arr, dtype=np.float64)
    if a.ndim != 1:
        raise ValueError(f"Expected 1D array, got ndim={a.ndim}")
    return a


def trim_nans(arr: NDArray[np.float64]) -> NDArray[np.float64]:
    """Return contiguous valid (non-NaN) slice from the end; empty if all NaN."""
    valid = ~np.isnan(arr)
    if not np.any(valid):
        return np.array([], dtype=np.float64)
    last_valid = np.where(valid)[0][-1]
    return arr[: last_valid + 1].copy()
