// EXACT layer (design D3): the generic B-spline kernel (design D2).
//
// Every evaluation/derivative algorithm is written ONCE against `VecSpace[V]`
// and instantiated for any vector type. A NURBS curve/surface is the perspective
// projection of a homogeneous B-spline (V = DVec4), so this kernel stays purely
// affine — the rational division happens in the projection wrappers (curve.mbt).
//
// `evaluate_many` is the batch hot-path (design D4): for sorted parameters the
// knot span advances monotonically, so span search is amortized O(1) per point
// instead of a binary search per call.

///|
/// A B-spline in an arbitrary vector space `V`. For NURBS, `V` is a homogeneous
/// vector (e.g. DVec4) and the wrapper projects by dividing through the weight.
pub(all) struct BSpline[V] {
  degree : Int
  knots : KnotVector
  ctrlpts : FixedArray[V]
}

///|
/// Construct a B-spline, enforcing degree >= 1, at least degree+1 control
/// points, and the knot-count relation `len(knots) == degree + num_ctrlpts + 1`.
pub fn[V] BSpline::new(
  degree : Int,
  knots : KnotVector,
  ctrlpts : FixedArray[V],
) -> BSpline[V]? {
  if degree < 1 {
    return None
  }
  if ctrlpts.length() < degree + 1 {
    return None
  }
  if knots.knots.length() != degree + ctrlpts.length() + 1 {
    return None
  }
  Some({ degree, knots, ctrlpts })
}

///|
pub fn[V] BSpline::num_ctrlpts(self : BSpline[V]) -> Int {
  self.ctrlpts.length()
}

///|
/// Evaluate the (affine) B-spline at `u`. Returns None outside the domain.
pub fn[V : VecSpace] BSpline::evaluate(self : BSpline[V], u : Double) -> V? {
  let n = self.ctrlpts.length() - 1
  if u < self.knots.knots[self.degree] || u > self.knots.knots[n + 1] {
    return None
  }
  let span = self.knots.find_span(self.degree, n, u)
  let basis = self.knots.basis_funs(span, self.degree, u)
  let mut acc = V::vzero()
  for j = 0; j <= self.degree; j = j + 1 {
    acc = acc.vadd(self.ctrlpts[span - self.degree + j].vscale(basis[j]))
  }
  Some(acc)
}

///|
/// Batch evaluation (design D4). `us` MUST be sorted ascending and within the
/// domain; otherwise returns None. The span advances monotonically across the
/// sweep, amortizing span search. Result order matches `us`.
pub fn[V : VecSpace] BSpline::evaluate_many(
  self : BSpline[V],
  us : FixedArray[Double],
) -> FixedArray[V]? {
  let n = self.ctrlpts.length() - 1
  let start = self.knots.knots[self.degree]
  let end = self.knots.knots[n + 1]
  // Validate sorted + in-domain in one pass.
  for i = 0; i < us.length(); i = i + 1 {
    if us[i] < start || us[i] > end {
      return None
    }
    if i > 0 && us[i] < us[i - 1] {
      return None
    }
  }
  let out : FixedArray[V] = FixedArray::make(us.length(), V::vzero())
  // Reuse the basis scratch buffers across the sweep (no per-point allocation).
  let p = self.degree
  let knots = self.knots.knots
  let basis : FixedArray[Double] = FixedArray::make(p + 1, 0.0)
  let left : FixedArray[Double] = FixedArray::make(p + 1, 0.0)
  let right : FixedArray[Double] = FixedArray::make(p + 1, 0.0)
  let mut span = p
  for i = 0; i < us.length(); i = i + 1 {
    let u = us[i]
    if u == end {
      span = n
    } else {
      while span < n && u >= knots[span + 1] {
        span = span + 1
      }
    }
    // Inline A2.2 basis functions into the reused buffers.
    basis[0] = 1.0
    for j = 1; j <= p; j = j + 1 {
      left[j] = u - knots[span + 1 - j]
      right[j] = knots[span + j] - u
      let mut saved = 0.0
      for r = 0; r < j; r = r + 1 {
        let temp = basis[r] / (right[r + 1] + left[j - r])
        basis[r] = saved + right[r + 1] * temp
        saved = left[j - r] * temp
      }
      basis[j] = saved
    }
    let mut acc = V::vzero()
    for j = 0; j <= p; j = j + 1 {
      acc = acc.vadd(self.ctrlpts[span - p + j].vscale(basis[j]))
    }
    out[i] = acc
  }
  Some(out)
}

///|
/// Homogeneous derivatives 0..d at `u` (row k is the k-th derivative). Returns
/// None outside the domain or if d > degree. The projection wrapper applies the
/// rational quotient rule to these homogeneous derivatives.
pub fn[V : VecSpace] BSpline::evaluate_derivatives(
  self : BSpline[V],
  u : Double,
  d : Int,
) -> Array[V]? {
  let n = self.ctrlpts.length() - 1
  if u < self.knots.knots[self.degree] || u > self.knots.knots[n + 1] {
    return None
  }
  if d > self.degree {
    return None
  }
  let span = self.knots.find_span(self.degree, n, u)
  let ders = self.knots.ders_basis_funs(span, self.degree, u, d)
  let out : Array[V] = []
  for k = 0; k <= d; k = k + 1 {
    let mut acc = V::vzero()
    for j = 0; j <= self.degree; j = j + 1 {
      acc = acc.vadd(self.ctrlpts[span - self.degree + j].vscale(ders[k][j]))
    }
    out.push(acc)
  }
  Some(out)
}