// APPROXIMATE layer (design D3): degree reduction (The NURBS Book Eqs 5.41/5.42).
// Reducing a Bézier segment's degree by 1 is exact only when the segment is
// genuinely degree-reducible; otherwise it is a least-squares-like approximation.
// The whole-curve operation decomposes, reduces each segment, links, and removes
// knots to restore the original join multiplicities.
// Reference: geomdl/helpers.py degree_reduction (right-hand recurrence corrected
// to descend, per the NURBS Book, so it is valid for all degrees).

///|
/// Degree-reduce a single Bézier segment by 1 (Eqs 5.41/5.42). `pts` has
/// degree+1 points; the result has degree points. None if degree < 2.
fn[V : VecSpace] bezier_reduce(
  degree : Int,
  pts : FixedArray[V],
) -> FixedArray[V]? {
  if degree < 2 {
    return None
  }
  let out : FixedArray[V] = FixedArray::make(degree, V::vzero())
  out[0] = pts[0]
  out[degree - 1] = pts[degree]
  if degree == 2 {
    return Some(out)
  }
  let p_is_odd = degree % 2 != 0
  let r = (degree - 1) / 2
  let r1 = if p_is_odd { r - 1 } else { r }
  // Left recurrence: out[1..r1].
  for i = 1; i <= r1; i = i + 1 {
    let alpha = i.to_double() / degree.to_double()
    out[i] = pts[i].vadd(out[i - 1].vscale(-alpha)).vscale(1.0 / (1.0 - alpha))
  }
  // Right recurrence (descending): out[degree-2 .. r1+1].
  let mut i = degree - 2
  while i >= r1 + 1 {
    let alpha = (i + 1).to_double() / degree.to_double()
    out[i] = pts[i + 1]
      .vadd(out[i + 1].vscale(-(1.0 - alpha)))
      .vscale(1.0 / alpha)
    i = i - 1
  }
  // Odd degree: average the two estimates of the middle control point.
  if p_is_odd {
    let alpha = r.to_double() / degree.to_double()
    let left = pts[r].vadd(out[r - 1].vscale(-alpha)).vscale(1.0 / (1.0 - alpha))
    let alpha2 = (r + 1).to_double() / degree.to_double()
    let right = pts[r + 1]
      .vadd(out[r + 1].vscale(-(1.0 - alpha2)))
      .vscale(1.0 / alpha2)
    out[r] = left.vadd(right).vscale(0.5)
  }
  Some(out)
}

///|
/// Degree-reduce the whole B-spline by 1 (approximate). Decompose into Bézier
/// segments, reduce each, link into a degree-(p-1) B-spline, then remove knots
/// to restore the original join multiplicities. None if degree < 2 or a join
/// cannot be restored within tolerance.
pub fn[V : VecSpace] BSpline::degree_reduce(
  self : BSpline[V],
  tol? : Double = 1.0e-7,
) -> BSpline[V]? {
  let p = self.degree
  if p < 2 {
    return None
  }
  let d = p - 1
  let segs = self.decompose_bezier()
  let red : Array[FixedArray[V]] = []
  for i = 0; i < segs.length(); i = i + 1 {
    let r = match bezier_reduce(p, segs[i].ctrlpts) {
      None => return None
      Some(x) => x
    }
    red.push(r)
  }
  // Link control points: first segment in full, then skip the shared endpoint.
  let new_pts : Array[V] = []
  for j = 0; j <= d; j = j + 1 {
    new_pts.push(red[0][j])
  }
  for i = 1; i < segs.length(); i = i + 1 {
    for j = 1; j <= d; j = j + 1 {
      new_pts.push(red[i][j])
    }
  }
  // Link knot vector: start^(d+1), each join^d, end^(d+1).
  let kv : Array[Double] = []
  let start = segs[0].knots.knots[0]
  let last_seg = segs[segs.length() - 1]
  let end = last_seg.knots.knots[last_seg.knots.knots.length() - 1]
  for j = 0; j <= d; j = j + 1 {
    kv.push(start)
  }
  for i = 1; i < segs.length(); i = i + 1 {
    let join = segs[i].knots.knots[0]
    for j = 0; j < d; j = j + 1 {
      kv.push(join)
    }
  }
  for j = 0; j <= d; j = j + 1 {
    kv.push(end)
  }
  let linked_kv = match KnotVector::new(FixedArray::from_array(kv)) {
    None => return None
    Some(x) => x
  }
  let mut result = match BSpline::new(d, linked_kv, FixedArray::from_array(new_pts)) {
    None => return None
    Some(x) => x
  }
  // Restore original join multiplicity s: remove d - s knots per join.
  for i = 1; i < segs.length(); i = i + 1 {
    let join = segs[i].knots.knots[0]
    let s = self.knots.multiplicity(join)
    let nremove = d - s
    if nremove > 0 {
      result = match result.remove_knot(join, tol=tol, r=nremove) {
        None => return None
        Some(x) => x
      }
    }
  }
  Some(result)
}

///|
pub fn NurbsCurve3::degree_reduce(
  self : NurbsCurve3,
  tol? : Double = 1.0e-7,
) -> NurbsCurve3? {
  match self.bspline.degree_reduce(tol=tol) {
    None => None
    Some(b) => Some({ bspline: b })
  }
}