// APPROXIMATE layer (design D3): bounding-volume hierarchy for accelerated
// closest-point queries. A curve BVH is built by recursive parameter splitting
// (knot insertion); each node bounds its segment by the axis-aligned box of the
// segment's control points (NURBS convex-hull property). Queries prune branches
// whose box is farther than the current best. Reference: verb Lazy*BoundingBoxTree;
// curvo/src/bounding_box/.

///|
struct BvhNode {
  min : @f64.DVec3
  max : @f64.DVec3
  left : Int // child index, -1 for a leaf
  right : Int
  u0 : Double
  u1 : Double
}

///|
/// A curve bounding-volume hierarchy (binary tree over parameter splits).
pub(all) struct CurveBvh {
  curve : NurbsCurve3
  nodes : Array[BvhNode]
  root : Int
}

///|
fn ctrl_bounds(curve : NurbsCurve3) -> (@f64.DVec3, @f64.DVec3) {
  let pts = curve.control_points()
  let mut mn = pts[0]
  let mut mx = pts[0]
  for i = 1; i < pts.length(); i = i + 1 {
    mn = mn.min(pts[i])
    mx = mx.max(pts[i])
  }
  (mn, mx)
}

///|
/// Squared distance from `point` to the box [mn, mx] (0 if inside).
fn box_dist_sq(mn : @f64.DVec3, mx : @f64.DVec3, point : @f64.DVec3) -> Double {
  let mut s = 0.0
  let dx = if point.x < mn.x {
    mn.x - point.x
  } else if point.x > mx.x {
    point.x - mx.x
  } else {
    0.0
  }
  let dy = if point.y < mn.y {
    mn.y - point.y
  } else if point.y > mx.y {
    point.y - mx.y
  } else {
    0.0
  }
  let dz = if point.z < mn.z {
    mn.z - point.z
  } else if point.z > mx.z {
    point.z - mx.z
  } else {
    0.0
  }
  s = dx * dx + dy * dy + dz * dz
  s
}

///|
fn build_node(
  curve : NurbsCurve3,
  u0 : Double,
  u1 : Double,
  depth : Int,
  max_depth : Int,
  nodes : Array[BvhNode],
) -> Int {
  let (mn, mx) = ctrl_bounds(curve)
  if depth >= max_depth {
    let idx = nodes.length()
    nodes.push({ min: mn, max: mx, left: -1, right: -1, u0, u1 })
    return idx
  }
  let mid = (u0 + u1) * 0.5
  match curve.split(mid) {
    None => {
      let idx = nodes.length()
      nodes.push({ min: mn, max: mx, left: -1, right: -1, u0, u1 })
      idx
    }
    Some((lc, rc)) => {
      let li = build_node(lc, u0, mid, depth + 1, max_depth, nodes)
      let ri = build_node(rc, mid, u1, depth + 1, max_depth, nodes)
      let idx = nodes.length()
      nodes.push({ min: mn, max: mx, left: li, right: ri, u0, u1 })
      idx
    }
  }
}

///|
/// Build a curve BVH by recursive splitting to `max_depth` (default 6).
pub fn NurbsCurve3::build_bvh(self : NurbsCurve3, max_depth? : Int = 6) -> CurveBvh {
  let n = self.bspline.ctrlpts.length() - 1
  let knots = self.bspline.knots.knots
  let u0 = knots[self.bspline.degree]
  let u1 = knots[n + 1]
  let nodes : Array[BvhNode] = []
  let root = build_node(self, u0, u1, 0, max_depth, nodes)
  { curve: self, nodes, root }
}

///|
priv struct ClosestState {
  mut dist : Double
  mut u : Double
}

///|
/// Bounded closest parameter over [u0, u1]: coarse sampling + BFGS refinement.
fn leaf_closest(
  curve : NurbsCurve3,
  u0 : Double,
  u1 : Double,
  point : @f64.DVec3,
) -> (Double, Double) {
  let ns = 12
  let mut best_u = u0
  let mut best_d = 1.0e300
  for i = 0; i <= ns; i = i + 1 {
    let u = u0 + (u1 - u0) * (i.to_double() / ns.to_double())
    match curve.point_at(u) {
      None => ()
      Some(p) => {
        let d = (p - point).length_sq()
        if d < best_d {
          best_d = d
          best_u = u
        }
      }
    }
  }
  let f = fn(x : FixedArray[Double]) -> Double {
    let u = clampd(x[0], u0, u1)
    match curve.point_at(u) {
      None => 1.0e300
      Some(p) => (p - point).length_sq()
    }
  }
  let grad = fn(x : FixedArray[Double]) -> FixedArray[Double] {
    let u = x[0]
    if u < u0 || u > u1 {
      return [0.0]
    }
    match curve.derivatives(u, 1) {
      None => [0.0]
      Some(d) => [2.0 * (d[0] - point).dot(d[1])]
    }
  }
  match bfgs(f, grad, [best_u], tol=1.0e-12) {
    None => (best_u, best_d)
    Some(sol) => {
      let uf = clampd(sol[0], u0, u1)
      match curve.point_at(uf) {
        None => (best_u, best_d)
        Some(p) => {
          let d = (p - point).length_sq()
          if d < best_d {
            (uf, d)
          } else {
            (best_u, best_d)
          }
        }
      }
    }
  }
}

///|
fn visit_bvh(
  nodes : Array[BvhNode],
  curve : NurbsCurve3,
  idx : Int,
  point : @f64.DVec3,
  state : ClosestState,
) -> Unit {
  let node = nodes[idx]
  if box_dist_sq(node.min, node.max, point) >= state.dist {
    return
  }
  if node.left < 0 {
    let (u, d) = leaf_closest(curve, node.u0, node.u1, point)
    if d < state.dist {
      state.dist = d
      state.u = u
    }
  } else {
    visit_bvh(nodes, curve, node.left, point, state)
    visit_bvh(nodes, curve, node.right, point, state)
  }
}

///|
/// Accelerated closest point via BVH traversal with box-distance pruning.
pub fn CurveBvh::closest_point(
  self : CurveBvh,
  point : @f64.DVec3,
) -> @f64.DVec3? {
  let state : ClosestState = { dist: 1.0e300, u: 0.0 }
  visit_bvh(self.nodes, self.curve, self.root, point, state)
  self.curve.point_at(state.u)
}