// APPROXIMATE / computational-geometry layer (M3): constrained Delaunay
// triangulation (CDT) of a 2D point set with required constraint edges. Builds a
// Delaunay triangulation by Bowyer–Watson incremental insertion, then recovers
// each constraint edge by flipping crossing edges. Used to mesh trimmed surface
// parameter domains with interior samples. Reference: curvo tessellation (spade
// CDT replacement); classic Bowyer–Watson + constraint recovery.

///|
fn tri_area2(a : @f64.DVec2, b : @f64.DVec2, c : @f64.DVec2) -> Double {
  (b - a).cross(c - a)
}

///|
fn make_ccw(
  pts : Array[@f64.DVec2],
  t : (Int, Int, Int),
) -> (Int, Int, Int) {
  let (a, b, c) = t
  if tri_area2(pts[a], pts[b], pts[c]) < 0.0 {
    (a, c, b)
  } else {
    t
  }
}

///|
/// Incircle predicate: is d inside the circumcircle of CCW triangle (a, b, c)?
fn in_circumcircle(
  a : @f64.DVec2,
  b : @f64.DVec2,
  c : @f64.DVec2,
  d : @f64.DVec2,
) -> Bool {
  let ax = a.x - d.x
  let ay = a.y - d.y
  let bx = b.x - d.x
  let by = b.y - d.y
  let cx = c.x - d.x
  let cy = c.y - d.y
  let det = (ax * ax + ay * ay) * (bx * cy - cx * by) -
    (bx * bx + by * by) * (ax * cy - cx * ay) +
    (cx * cx + cy * cy) * (ax * by - bx * ay)
  det > 1.0e-12
}

///|
fn has_edge(tris : Array[(Int, Int, Int)], a : Int, b : Int) -> Bool {
  for i = 0; i < tris.length(); i = i + 1 {
    let (x, y, z) = tris[i]
    if (x == a && y == b) || (y == a && x == b) ||
      (y == a && z == b) || (z == a && y == b) ||
      (z == a && x == b) || (x == a && z == b) {
      return true
    }
  }
  false
}

///|
/// Proper segment intersection (excluding shared endpoints).
fn segments_cross(
  p1 : @f64.DVec2,
  p2 : @f64.DVec2,
  p3 : @f64.DVec2,
  p4 : @f64.DVec2,
) -> Bool {
  let d1 = tri_area2(p3, p4, p1)
  let d2 = tri_area2(p3, p4, p2)
  let d3 = tri_area2(p1, p2, p3)
  let d4 = tri_area2(p1, p2, p4)
  ((d1 > 0.0 && d2 < 0.0) || (d1 < 0.0 && d2 > 0.0)) &&
  ((d3 > 0.0 && d4 < 0.0) || (d3 < 0.0 && d4 > 0.0))
}

///|
/// Constrained Delaunay triangulation. `constraints` are index pairs that must
/// appear as edges. Returns CCW triangle index triples (no super-triangle verts).
pub fn cdt(
  points : Array[@f64.DVec2],
  constraints : Array[(Int, Int)],
) -> Array[(Int, Int, Int)] {
  let n = points.length()
  if n < 3 {
    return []
  }
  let mut minx = points[0].x
  let mut maxx = points[0].x
  let mut miny = points[0].y
  let mut maxy = points[0].y
  for i = 1; i < n; i = i + 1 {
    if points[i].x < minx {
      minx = points[i].x
    }
    if points[i].x > maxx {
      maxx = points[i].x
    }
    if points[i].y < miny {
      miny = points[i].y
    }
    if points[i].y > maxy {
      maxy = points[i].y
    }
  }
  let dx = maxx - minx
  let dy = maxy - miny
  let dmax = (if dx > dy { dx } else { dy }) * 20.0 + 1.0
  let midx = (minx + maxx) * 0.5
  let midy = (miny + maxy) * 0.5
  let pts : Array[@f64.DVec2] = []
  for i = 0; i < n; i = i + 1 {
    pts.push(points[i])
  }
  pts.push(@f64.DVec2::new(midx - dmax, midy - dmax)) // n
  pts.push(@f64.DVec2::new(midx + dmax, midy - dmax)) // n+1
  pts.push(@f64.DVec2::new(midx, midy + dmax)) // n+2
  let tris : Array[(Int, Int, Int)] = [(n, n + 1, n + 2)]
  for i = 0; i < n; i = i + 1 {
    let p = pts[i]
    let bad : Array[Int] = []
    for t = 0; t < tris.length(); t = t + 1 {
      let (a, b, c) = tris[t]
      if in_circumcircle(pts[a], pts[b], pts[c], p) {
        bad.push(t)
      }
    }
    // Boundary edges of the cavity: edges appearing in exactly one bad triangle.
    let boundary : Array[(Int, Int)] = []
    for bi = 0; bi < bad.length(); bi = bi + 1 {
      let (a, b, c) = tris[bad[bi]]
      let edges : Array[(Int, Int)] = [(a, b), (b, c), (c, a)]
      for e = 0; e < 3; e = e + 1 {
        let (u, v) = edges[e]
        let mut shared = false
        for bj = 0; bj < bad.length(); bj = bj + 1 {
          if bj == bi {
            continue
          }
          let (x, y, z) = tris[bad[bj]]
          if (x == v && y == u) || (y == v && z == u) || (z == v && x == u) ||
            (x == u && y == v) || (y == u && z == v) || (z == u && x == v) {
            shared = true
            break
          }
        }
        if !shared {
          boundary.push((u, v))
        }
      }
    }
    // Rebuild without the bad triangles.
    let keep : Array[(Int, Int, Int)] = []
    for t = 0; t < tris.length(); t = t + 1 {
      let mut is_bad = false
      for bi = 0; bi < bad.length(); bi = bi + 1 {
        if bad[bi] == t {
          is_bad = true
          break
        }
      }
      if !is_bad {
        keep.push(tris[t])
      }
    }
    tris.clear()
    for t = 0; t < keep.length(); t = t + 1 {
      tris.push(keep[t])
    }
    for e = 0; e < boundary.length(); e = e + 1 {
      let (u, v) = boundary[e]
      tris.push(make_ccw(pts, (u, v, i)))
    }
  }
  // Drop super-triangle vertices.
  let result : Array[(Int, Int, Int)] = []
  for t = 0; t < tris.length(); t = t + 1 {
    let (a, b, c) = tris[t]
    if a < n && b < n && c < n {
      result.push(make_ccw(pts, (a, b, c)))
    }
  }
  // Recover constraint edges by flipping crossing edges.
  for ci = 0; ci < constraints.length(); ci = ci + 1 {
    let (a, b) = constraints[ci]
    let mut iter = 0
    while !has_edge(result, a, b) && iter < 1000 {
      iter = iter + 1
      // Find an edge crossing segment a-b and flip it.
      let mut flipped = false
      for t = 0; t < result.length() && !flipped; t = t + 1 {
        let (x, y, z) = result[t]
        let edges : Array[(Int, Int)] = [(x, y), (y, z), (z, x)]
        for e = 0; e < 3; e = e + 1 {
          let (u, v) = edges[e]
          if u == a || u == b || v == a || v == b {
            continue
          }
          if segments_cross(pts[a], pts[b], pts[u], pts[v]) {
            // Find the neighbor triangle across edge (u, v).
            let mut nt = -1
            for t2 = 0; t2 < result.length(); t2 = t2 + 1 {
              if t2 == t {
                continue
              }
              let (x2, y2, z2) = result[t2]
              if (x2 == v && y2 == u) || (y2 == v && z2 == u) || (z2 == v && x2 == u) ||
                (x2 == u && y2 == v) || (y2 == u && z2 == v) || (z2 == u && x2 == v) {
                nt = t2
                break
              }
            }
            if nt < 0 {
              continue
            }
            let (x2, y2, z2) = result[nt]
            let w = if x2 != u && x2 != v {
              x2
            } else if y2 != u && y2 != v {
              y2
            } else {
              z2
            }
            let opp = if x != u && x != v {
              x
            } else if y != u && y != v {
              y
            } else {
              z
            }
            // Flip diagonal u-v to opp-w; require convex quad.
            if tri_area2(pts[opp], pts[u], pts[w]) > 0.0 &&
              tri_area2(pts[opp], pts[w], pts[v]) > 0.0 {
              let t1 = make_ccw(pts, (opp, u, w))
              let t2n = make_ccw(pts, (opp, w, v))
              let hi = if t > nt { t } else { nt }
              let lo = if t > nt { nt } else { t }
              ignore(result.remove(hi))
              ignore(result.remove(lo))
              result.push(t1)
              result.push(t2n)
              flipped = true
              break
            }
          }
        }
      }
      if !flipped {
        break
      }
    }
  }
  result
}