// EXACT layer (design D1/D3): surface tessellation into a NEUTRAL mesh record.
// The core stays math-only — it outputs parametric-sample data (positions /
// normals / uvs / indices as Double vectors), NOT the geometry module's MeshData.
// The optional adapter module `tycho_nurbs_mesh` converts this to MeshData (ports
// & adapters, design D1).
//
// Two modes: a uniform parameter grid (`tessellate`) and curvature-adaptive
// (`tessellate_adaptive`). The adaptive mode recursively subdivides each parameter
// direction where the surface deviates from its chord by more than a tolerance,
// then meshes the tensor product of the two break sets — crack-free (no hanging
// nodes) because every u-break spans all v and vice versa.
//
// Winding: triangles are CCW relative to the analytic normal S_u x S_v. UVs are
// the normalized (u, v) surface parameters.

///|
/// A neutral triangle mesh in Double precision. Core output; the mesh adapter
/// down-casts to Float `MeshData` at the boundary.
pub(all) struct Tessellation {
  positions : FixedArray[@f64.DVec3]
  normals : FixedArray[@f64.DVec3]
  uvs : FixedArray[@f64.DVec2]
  indices : FixedArray[UInt]
}

///|
/// Build a mesh from explicit parameter break sets (tensor product). `us`/`vs`
/// are ascending and include the domain endpoints.
fn tessellation_from_breaks(
  srf : NurbsSurface3,
  us : FixedArray[Double],
  vs : FixedArray[Double],
) -> Tessellation? {
  let rows = us.length()
  let cols = vs.length()
  if rows < 2 || cols < 2 {
    return None
  }
  let nverts = rows * cols
  let positions : FixedArray[@f64.DVec3] = FixedArray::make(nverts, @f64.DVec3::zero())
  let normals : FixedArray[@f64.DVec3] = FixedArray::make(nverts, @f64.DVec3::zero())
  let uvs : FixedArray[@f64.DVec2] = FixedArray::make(nverts, @f64.DVec2::zero())
  let u0 = us[0]
  let u1 = us[rows - 1]
  let v0 = vs[0]
  let v1 = vs[cols - 1]
  let du = u1 - u0
  let dv = v1 - v0
  for i = 0; i < rows; i = i + 1 {
    for j = 0; j < cols; j = j + 1 {
      let idx = i * cols + j
      let u = us[i]
      let v = vs[j]
      positions[idx] = match srf.point_at(u, v) {
        None => return None
        Some(x) => x
      }
      normals[idx] = match srf.normal_at(u, v) {
        None => @f64.DVec3::zero()
        Some(x) => x
      }
      let tu = if du == 0.0 { 0.0 } else { (u - u0) / du }
      let tv = if dv == 0.0 { 0.0 } else { (v - v0) / dv }
      uvs[idx] = @f64.DVec2::new(tu, tv)
    }
  }
  let ntris = 2 * (rows - 1) * (cols - 1)
  let indices : FixedArray[UInt] = FixedArray::make(ntris * 3, (0 : UInt))
  let mut t = 0
  for i = 0; i < rows - 1; i = i + 1 {
    for j = 0; j < cols - 1; j = j + 1 {
      let a = i * cols + j
      let b = (i + 1) * cols + j
      let c = i * cols + (j + 1)
      let d = (i + 1) * cols + (j + 1)
      indices[t] = a.reinterpret_as_uint()
      indices[t + 1] = b.reinterpret_as_uint()
      indices[t + 2] = d.reinterpret_as_uint()
      indices[t + 3] = a.reinterpret_as_uint()
      indices[t + 4] = d.reinterpret_as_uint()
      indices[t + 5] = c.reinterpret_as_uint()
      t = t + 6
    }
  }
  Some({ positions, normals, uvs, indices })
}

///|
/// Tessellate on a uniform (segs_u x segs_v) parameter grid. None if segs < 1.
pub fn NurbsSurface3::tessellate(
  self : NurbsSurface3,
  segs_u : Int,
  segs_v : Int,
) -> Tessellation? {
  if segs_u < 1 || segs_v < 1 {
    return None
  }
  let nu = self.num_u()
  let nv = self.num_v()
  let ku = self.knots_u.knots
  let kv = self.knots_v.knots
  let u0 = ku[self.degree_u]
  let u1 = ku[nu]
  let v0 = kv[self.degree_v]
  let v1 = kv[nv]
  let us : FixedArray[Double] = FixedArray::make(segs_u + 1, 0.0)
  let vs : FixedArray[Double] = FixedArray::make(segs_v + 1, 0.0)
  for i = 0; i <= segs_u; i = i + 1 {
    us[i] = u0 + (u1 - u0) * (i.to_double() / segs_u.to_double())
  }
  for j = 0; j <= segs_v; j = j + 1 {
    vs[j] = v0 + (v1 - v0) * (j.to_double() / segs_v.to_double())
  }
  tessellation_from_breaks(self, us, vs)
}

///|
/// Max chord deviation of the u-iso-curves over [a, b] at midpoint `mid`,
/// sampled at the given v values.
fn chord_deviation_u(
  srf : NurbsSurface3,
  a : Double,
  b : Double,
  mid : Double,
  vs : FixedArray[Double],
) -> Double {
  let mut dev = 0.0
  for j = 0; j < vs.length(); j = j + 1 {
    let v = vs[j]
    match (srf.point_at(a, v), srf.point_at(b, v), srf.point_at(mid, v)) {
      (Some(pa), Some(pb), Some(pm)) => {
        let d = (pm - (pa + pb).scale(0.5)).length()
        if d > dev {
          dev = d
        }
      }
      _ => ()
    }
  }
  dev
}

///|
fn chord_deviation_v(
  srf : NurbsSurface3,
  a : Double,
  b : Double,
  mid : Double,
  us : FixedArray[Double],
) -> Double {
  let mut dev = 0.0
  for i = 0; i < us.length(); i = i + 1 {
    let u = us[i]
    match (srf.point_at(u, a), srf.point_at(u, b), srf.point_at(u, mid)) {
      (Some(pa), Some(pb), Some(pm)) => {
        let d = (pm - (pa + pb).scale(0.5)).length()
        if d > dev {
          dev = d
        }
      }
      _ => ()
    }
  }
  dev
}

///|
fn refine_u(
  srf : NurbsSurface3,
  a : Double,
  b : Double,
  vs : FixedArray[Double],
  tol : Double,
  depth : Int,
  max_depth : Int,
  out : Array[Double],
) -> Unit {
  if depth >= max_depth {
    return
  }
  let mid = (a + b) * 0.5
  if chord_deviation_u(srf, a, b, mid, vs) > tol {
    refine_u(srf, a, mid, vs, tol, depth + 1, max_depth, out)
    out.push(mid)
    refine_u(srf, mid, b, vs, tol, depth + 1, max_depth, out)
  }
}

///|
fn refine_v(
  srf : NurbsSurface3,
  a : Double,
  b : Double,
  us : FixedArray[Double],
  tol : Double,
  depth : Int,
  max_depth : Int,
  out : Array[Double],
) -> Unit {
  if depth >= max_depth {
    return
  }
  let mid = (a + b) * 0.5
  if chord_deviation_v(srf, a, b, mid, us) > tol {
    refine_v(srf, a, mid, us, tol, depth + 1, max_depth, out)
    out.push(mid)
    refine_v(srf, mid, b, us, tol, depth + 1, max_depth, out)
  }
}

///|
/// Curvature-adaptive tessellation: recursively subdivide each parameter
/// direction where the chord deviation exceeds `chord_tol` (up to `max_depth`),
/// then mesh the tensor product of the break sets. Flat regions stay coarse;
/// curved regions refine. Crack-free. None on invalid tolerance/depth.
pub fn NurbsSurface3::tessellate_adaptive(
  self : NurbsSurface3,
  chord_tol? : Double = 1.0e-3,
  max_depth? : Int = 8,
) -> Tessellation? {
  if chord_tol <= 0.0 || max_depth < 0 {
    return None
  }
  let nu = self.num_u()
  let nv = self.num_v()
  let ku = self.knots_u.knots
  let kv = self.knots_v.knots
  let u0 = ku[self.degree_u]
  let u1 = ku[nu]
  let v0 = kv[self.degree_v]
  let v1 = kv[nv]
  let v_probe : FixedArray[Double] = [v0, (v0 + v1) * 0.5, v1]
  let u_probe : FixedArray[Double] = [u0, (u0 + u1) * 0.5, u1]
  let u_mids : Array[Double] = []
  let v_mids : Array[Double] = []
  refine_u(self, u0, u1, v_probe, chord_tol, 0, max_depth, u_mids)
  refine_v(self, v0, v1, u_probe, chord_tol, 0, max_depth, v_mids)
  let us : FixedArray[Double] = FixedArray::make(u_mids.length() + 2, 0.0)
  us[0] = u0
  for i = 0; i < u_mids.length(); i = i + 1 {
    us[i + 1] = u_mids[i]
  }
  us[us.length() - 1] = u1
  let vs : FixedArray[Double] = FixedArray::make(v_mids.length() + 2, 0.0)
  vs[0] = v0
  for j = 0; j < v_mids.length(); j = j + 1 {
    vs[j + 1] = v_mids[j]
  }
  vs[vs.length() - 1] = v1
  tessellation_from_breaks(self, us, vs)
}