// EXACT layer (design D3): arc length via fixed-order Gauss–Legendre quadrature
// of the speed |C'(u)|, integrated span-by-span (the curve is smooth within each
// knot span). The quadrature nodes/weights are computed self-containedly by
// Newton iteration on Legendre polynomial roots — no external gauss-quad crate,
// no magic constant table (replaces curvo's gauss-quad dependency).
//
// Arc-length parameter inversion uses monotone bisection. Reference: The NURBS
// Book arc-length discussion; curvo/src/curve/nurbs_curve.rs (gauss-quad usage).

///|
/// Gauss–Legendre nodes and weights on [-1, 1] for order `n`, computed via
/// Newton iteration on the roots of the Legendre polynomial P_n.
fn gauss_legendre(n : Int) -> (FixedArray[Double], FixedArray[Double]) {
  let nodes : FixedArray[Double] = FixedArray::make(n, 0.0)
  let weights : FixedArray[Double] = FixedArray::make(n, 0.0)
  let pi = 3.141592653589793
  let half = (n + 1) / 2
  for i = 0; i < half; i = i + 1 {
    let mut z = @math.cos(pi * (i.to_double() + 0.75) / (n.to_double() + 0.5))
    let mut pp = 0.0
    let mut iter = 0
    while iter < 100 {
      let mut p1 = 1.0
      let mut p2 = 0.0
      for j = 0; j < n; j = j + 1 {
        let p3 = p2
        p2 = p1
        p1 = ((2 * j + 1).to_double() * z * p2 - j.to_double() * p3) /
          (j + 1).to_double()
      }
      // p1 = P_n(z), p2 = P_{n-1}(z); P_n'(z) = n (z P_n - P_{n-1}) / (z^2 - 1).
      pp = n.to_double() * (z * p1 - p2) / (z * z - 1.0)
      let z1 = z
      z = z1 - p1 / pp
      if (z - z1).abs() < 1.0e-15 {
        break
      }
      iter = iter + 1
    }
    nodes[i] = -z
    nodes[n - 1 - i] = z
    let w = 2.0 / ((1.0 - z * z) * pp * pp)
    weights[i] = w
    weights[n - 1 - i] = w
  }
  (nodes, weights)
}

///|
/// Integrate the speed over [a, b] with the given Gauss–Legendre rule.
fn integrate_speed(
  c : NurbsCurve3,
  a : Double,
  b : Double,
  nodes : FixedArray[Double],
  weights : FixedArray[Double],
) -> Double? {
  if a == b {
    return Some(0.0)
  }
  let half = (b - a) * 0.5
  let mid = (a + b) * 0.5
  let mut sum = 0.0
  for i = 0; i < nodes.length(); i = i + 1 {
    let u = mid + half * nodes[i]
    let ders = match c.derivatives(u, 1) {
      None => return None
      Some(d) => d
    }
    sum = sum + weights[i] * ders[1].length()
  }
  Some(sum * half)
}

///|
/// Arc length over [u0, u1] (defaults to the full domain). Integrates span by
/// span with a 16-point Gauss–Legendre rule. None if the interval is invalid.
pub fn NurbsCurve3::arc_length(
  self : NurbsCurve3,
  u0? : Double,
  u1? : Double,
) -> Double? {
  let p = self.bspline.degree
  let n = self.bspline.ctrlpts.length() - 1
  let knots = self.bspline.knots.knots
  let start = match u0 {
    Some(x) => x
    None => knots[p]
  }
  let end = match u1 {
    Some(x) => x
    None => knots[n + 1]
  }
  if start < knots[p] || end > knots[n + 1] || start > end {
    return None
  }
  if start == end {
    return Some(0.0)
  }
  let (nodes, weights) = gauss_legendre(16)
  let mut total = 0.0
  let mut a = start
  for i = p + 1; i <= n; i = i + 1 {
    let k = knots[i]
    if k > a && k < end {
      let seg = match integrate_speed(self, a, k, nodes, weights) {
        None => return None
        Some(x) => x
      }
      total = total + seg
      a = k
    }
  }
  let seg = match integrate_speed(self, a, end, nodes, weights) {
    None => return None
    Some(x) => x
  }
  Some(total + seg)
}

///|
/// Invert arc length: find the parameter `u` whose arc length from the domain
/// start equals `s`, via monotone bisection. None if s is outside [0, total].
pub fn NurbsCurve3::arc_length_parameter(
  self : NurbsCurve3,
  s : Double,
  tol? : Double = 1.0e-10,
) -> Double? {
  let p = self.bspline.degree
  let n = self.bspline.ctrlpts.length() - 1
  let knots = self.bspline.knots.knots
  let start = knots[p]
  let end = knots[n + 1]
  let total = match self.arc_length() {
    None => return None
    Some(x) => x
  }
  // Tolerate rounding overshoot at the endpoints, but reject genuine out-of-range.
  if s < 0.0 || s > total + 1.0e-9 {
    return None
  }
  let target = if s > total { total } else { s }
  if target == 0.0 {
    return Some(start)
  }
  if target == total {
    return Some(end)
  }
  let mut lo = start
  let mut hi = end
  let mut iter = 0
  while iter < 80 {
    let mid = (lo + hi) * 0.5
    let len = match self.arc_length(u1=mid) {
      None => return None
      Some(x) => x
    }
    if (len - target).abs() < tol {
      return Some(mid)
    }
    if len < target {
      lo = mid
    } else {
      hi = mid
    }
    iter = iter + 1
  }
  Some((lo + hi) * 0.5)
}