// APPROXIMATE layer (design D3/D4): least-squares curve and surface fitting.
// Curve fitting follows The NURBS Book pp.410-413 (Eq 9.63/9.67) with the knot
// vector of Eq 9.68/9.69, but solves the collocation system by Householder QR
// (design D4) instead of geomdl's normal equations, avoiding the squared
// condition number. Surface fitting composes separable u- then v-direction curve
// fits. References: geomdl/fitting.py approximate_curve / approximate_surface.

///|
/// Fitting knot vector (Eq 9.68/9.69): every knot span contains at least one
/// parameter. `num_cpts` control points, `num_dpts` data points, parameters `uk`.
fn fit_knots(
  degree : Int,
  num_dpts : Int,
  num_cpts : Int,
  uk : FixedArray[Double],
) -> KnotVector? {
  let len = num_cpts + degree + 1
  let kv : FixedArray[Double] = FixedArray::make(len, 0.0)
  let d = num_dpts.to_double() / (num_cpts - degree).to_double()
  for j = 1; j <= num_cpts - degree - 1; j = j + 1 {
    let jd = j.to_double() * d
    let i = jd.to_int()
    let alpha = jd - i.to_double()
    kv[degree + j] = (1.0 - alpha) * uk[i - 1] + alpha * uk[i]
  }
  for i = num_cpts; i < len; i = i + 1 {
    kv[i] = 1.0
  }
  KnotVector::new(kv)
}

///|
/// Least-squares fit of a curve to data points with a fixed number of control
/// points `num_cpts` (default num_points-1, which interpolates). Endpoints are
/// fixed to the first/last data points; interior control points solve the
/// overdetermined collocation system via QR. None on invalid sizes.
pub fn NurbsCurve3::fit(
  points : FixedArray[@f64.DVec3],
  degree : Int,
  num_cpts? : Int,
  param? : ParamMethod = ChordLength,
) -> NurbsCurve3? {
  let num_dpts = points.length()
  let nc = match num_cpts {
    Some(x) => x
    None => num_dpts - 1
  }
  if degree < 1 || num_dpts < 2 || nc < degree + 1 || nc > num_dpts - 1 {
    return None
  }
  let uk = match interp_params(points, param) {
    None => return None
    Some(x) => x
  }
  let kv = match fit_knots(degree, num_dpts, nc, uk) {
    None => return None
    Some(x) => x
  }
  let n = nc - 1
  let ctrl : FixedArray[@f64.DVec3] = FixedArray::make(nc, @f64.DVec3::zero())
  ctrl[0] = points[0]
  ctrl[nc - 1] = points[num_dpts - 1]
  let rows = num_dpts - 2
  let cols = nc - 2
  if rows >= 1 && cols >= 1 {
    let mat = dmat(rows, cols)
    let rkx : FixedArray[Double] = FixedArray::make(rows, 0.0)
    let rky : FixedArray[Double] = FixedArray::make(rows, 0.0)
    let rkz : FixedArray[Double] = FixedArray::make(rows, 0.0)
    for i = 1; i <= num_dpts - 2; i = i + 1 {
      let u = uk[i]
      let n0 = kv.basis_one(degree, n, 0, u)
      let nn = kv.basis_one(degree, n, n, u)
      rkx[i - 1] = points[i].x - n0 * points[0].x - nn * points[num_dpts - 1].x
      rky[i - 1] = points[i].y - n0 * points[0].y - nn * points[num_dpts - 1].y
      rkz[i - 1] = points[i].z - n0 * points[0].z - nn * points[num_dpts - 1].z
      for j = 1; j <= nc - 2; j = j + 1 {
        dmat_set(mat, i - 1, j - 1, kv.basis_one(degree, n, j, u))
      }
    }
    let px = match qr_solve(mat, rkx) {
      None => return None
      Some(x) => x
    }
    let py = match qr_solve(mat, rky) {
      None => return None
      Some(x) => x
    }
    let pz = match qr_solve(mat, rkz) {
      None => return None
      Some(x) => x
    }
    for j = 1; j <= nc - 2; j = j + 1 {
      ctrl[j] = @f64.DVec3::new(px[j - 1], py[j - 1], pz[j - 1])
    }
  }
  NurbsCurve3::from_points(degree, kv, ctrl)
}

///|
/// Least-squares fit of a non-rational surface to a row-major grid of data points
/// (size_u columns x size_v rows), by separable u- then v-direction curve fits
/// with uniform parameters (so knot vectors stay consistent across rows/columns).
pub fn NurbsSurface3::fit(
  points : FixedArray[@f64.DVec3],
  size_u : Int,
  size_v : Int,
  degree_u : Int,
  degree_v : Int,
  num_cpts_u? : Int,
  num_cpts_v? : Int,
) -> NurbsSurface3? {
  if size_u < 2 || size_v < 2 || points.length() != size_u * size_v {
    return None
  }
  let ncu = match num_cpts_u {
    Some(x) => x
    None => size_u - 1
  }
  let ncv = match num_cpts_v {
    Some(x) => x
    None => size_v - 1
  }
  // Step 1: fit each v-row in the u direction.
  let row_ctrl : Array[FixedArray[@f64.DVec3]] = []
  let mut knots_u : KnotVector? = None
  for l = 0; l < size_v; l = l + 1 {
    let row_pts : FixedArray[@f64.DVec3] = FixedArray::make(size_u, @f64.DVec3::zero())
    for i = 0; i < size_u; i = i + 1 {
      row_pts[i] = points[l * size_u + i]
    }
    let c = match NurbsCurve3::fit(row_pts, degree_u, num_cpts=ncu, param=Uniform) {
      None => return None
      Some(x) => x
    }
    row_ctrl.push(c.control_points())
    knots_u = Some(c.bspline.knots)
  }
  let ku = match knots_u {
    None => return None
    Some(x) => x
  }
  // Step 2: fit each u-column of intermediate control points in the v direction.
  let col_ctrl : Array[FixedArray[@f64.DVec3]] = []
  let mut knots_v : KnotVector? = None
  for i = 0; i < ncu; i = i + 1 {
    let col_pts : FixedArray[@f64.DVec3] = FixedArray::make(size_v, @f64.DVec3::zero())
    for l = 0; l < size_v; l = l + 1 {
      col_pts[l] = row_ctrl[l][i]
    }
    let c = match NurbsCurve3::fit(col_pts, degree_v, num_cpts=ncv, param=Uniform) {
      None => return None
      Some(x) => x
    }
    col_ctrl.push(c.control_points())
    knots_v = Some(c.bspline.knots)
  }
  let kv = match knots_v {
    None => return None
    Some(x) => x
  }
  let grid : FixedArray[@f64.DVec3] = FixedArray::make(ncu * ncv, @f64.DVec3::zero())
  for i = 0; i < ncu; i = i + 1 {
    for j = 0; j < ncv; j = j + 1 {
      grid[i * ncv + j] = col_ctrl[i][j]
    }
  }
  NurbsSurface3::from_points(degree_u, degree_v, ku, kv, grid)
}