// EXACT layer (design D3): NURBS curve = perspective projection of a homogeneous
// B-spline (design D2 factorization). The kernel (bspline.mbt) does the affine
// work in DVec4; this wrapper divides by the weight at the very end.
//
// Rational derivatives follow The NURBS Book A4.2 (quotient rule with binomial
// recursion). No tolerance parameter appears here — projection is exact.

///|
/// A 3D NURBS curve, stored as a homogeneous (DVec4) B-spline. Control points
/// are kept in homogeneous form (x*w, y*w, z*w, w) so knot/degree algorithms
/// stay affine; friendly point/weight views are provided at the boundary.
pub(all) struct NurbsCurve3 {
  bspline : BSpline[@f64.DVec4]
}

///|
/// Build from Cartesian points + positive weights. Rejects mismatched lengths
/// or non-positive weights (negative-weight conic representations are a later,
/// explicitly-opt-in feature).
pub fn NurbsCurve3::from_points_weights(
  degree : Int,
  knots : KnotVector,
  points : FixedArray[@f64.DVec3],
  weights : FixedArray[Double],
) -> NurbsCurve3? {
  if points.length() != weights.length() {
    return None
  }
  let hw : FixedArray[@f64.DVec4] = FixedArray::make(
    points.length(),
    @f64.DVec4::zero(),
  )
  for i = 0; i < points.length(); i = i + 1 {
    let w = weights[i]
    if w <= 0.0 {
      return None
    }
    hw[i] = points[i].scale(w).extend_w(w)
  }
  let bspline = BSpline::new(degree, knots, hw)
  match bspline {
    None => None
    Some(b) => Some({ bspline: b })
  }
}

///|
/// Build a non-rational B-spline curve (all weights 1).
pub fn NurbsCurve3::from_points(
  degree : Int,
  knots : KnotVector,
  points : FixedArray[@f64.DVec3],
) -> NurbsCurve3? {
  let weights : FixedArray[Double] = FixedArray::make(points.length(), 1.0)
  NurbsCurve3::from_points_weights(degree, knots, points, weights)
}

///|
/// Build directly from homogeneous (DVec4) control points (x*w, y*w, z*w, w).
/// Used by constructors that transform control points in homogeneous space.
pub fn NurbsCurve3::new_homogeneous(
  degree : Int,
  knots : KnotVector,
  ctrlpts : FixedArray[@f64.DVec4],
) -> NurbsCurve3? {
  match BSpline::new(degree, knots, ctrlpts) {
    None => None
    Some(b) => Some({ bspline: b })
  }
}

///|
pub fn NurbsCurve3::degree(self : NurbsCurve3) -> Int {
  self.bspline.degree
}

///|
pub fn NurbsCurve3::num_ctrlpts(self : NurbsCurve3) -> Int {
  self.bspline.ctrlpts.length()
}

///|
/// Cartesian control points (homogeneous xyz divided by w).
pub fn NurbsCurve3::control_points(self : NurbsCurve3) -> FixedArray[@f64.DVec3] {
  let n = self.bspline.ctrlpts.length()
  let out : FixedArray[@f64.DVec3] = FixedArray::make(n, @f64.DVec3::zero())
  for i = 0; i < n; i = i + 1 {
    let p = self.bspline.ctrlpts[i]
    out[i] = p.xyz().scale(1.0 / p.w)
  }
  out
}

///|
pub fn NurbsCurve3::weights(self : NurbsCurve3) -> FixedArray[Double] {
  let n = self.bspline.ctrlpts.length()
  let out : FixedArray[Double] = FixedArray::make(n, 0.0)
  for i = 0; i < n; i = i + 1 {
    out[i] = self.bspline.ctrlpts[i].w
  }
  out
}

///|
/// Project a homogeneous point to Cartesian; None if w == 0 (point at infinity).
fn project(p : @f64.DVec4) -> @f64.DVec3? {
  if p.w == 0.0 {
    None
  } else {
    Some(p.xyz().scale(1.0 / p.w))
  }
}

///|
/// Evaluate the curve at `u`. None outside the domain or at a zero-weight point.
pub fn NurbsCurve3::point_at(self : NurbsCurve3, u : Double) -> @f64.DVec3? {
  match self.bspline.evaluate(u) {
    None => None
    Some(p) => project(p)
  }
}

///|
/// Batch projection (design D4). `us` must be sorted ascending and in-domain.
pub fn NurbsCurve3::evaluate_many(
  self : NurbsCurve3,
  us : FixedArray[Double],
) -> FixedArray[@f64.DVec3]? {
  let hw = self.bspline.evaluate_many(us)
  match hw {
    None => None
    Some(pts) => {
      let out : FixedArray[@f64.DVec3] = FixedArray::make(
        pts.length(),
        @f64.DVec3::zero(),
      )
      for i = 0; i < pts.length(); i = i + 1 {
        match project(pts[i]) {
          None => return None
          Some(p) => out[i] = p
        }
      }
      Some(out)
    }
  }
}

///|
/// Binomial coefficient C(n, k) for the rational derivative recursion.
fn binom(n : Int, k : Int) -> Int {
  if k < 0 || k > n {
    return 0
  }
  let mut r = 1
  for i = 0; i < k; i = i + 1 {
    r = r * (n - i) / (i + 1)
  }
  r
}

///|
/// Rational derivatives 0..d at `u` (The NURBS Book A4.2). Row 0 is the point,
/// row 1 the tangent, etc. None outside the domain, if d > degree, or w == 0.
pub fn NurbsCurve3::derivatives(
  self : NurbsCurve3,
  u : Double,
  d : Int,
) -> Array[@f64.DVec3]? {
  let hw = self.bspline.evaluate_derivatives(u, d)
  match hw {
    None => None
    Some(hd) => {
      let w0 = hd[0].w
      if w0 == 0.0 {
        return None
      }
      let out : Array[@f64.DVec3] = []
      out.push(hd[0].xyz().scale(1.0 / w0))
      for k = 1; k <= d; k = k + 1 {
        let mut numer = hd[k].xyz()
        for i = 1; i <= k; i = i + 1 {
          let coeff = binom(k, i).to_double() * hd[i].w
          numer = numer - out[k - i].scale(coeff)
        }
        out.push(numer.scale(1.0 / w0))
      }
      Some(out)
    }
  }
}