// APPROXIMATE / computational-geometry layer (M3): 2D polygon boolean operations.
// Curves are flattened to polylines (TrimmedCurve2::flatten / sampling) before
// boolean, the standard CAD pipeline. Provides segment intersection, point-in-
// polygon, Sutherland–Hodgman convex clipping, and Greiner–Hormann boolean
// (union / intersection / difference) for simple polygons. References:
// curvo/src/boolean/; verb; classic computational-geometry algorithms.

///|
pub(all) enum BoolOp {
  Intersection
  Union
  Difference
}

///|
/// Segment intersection p1->p2 with p3->p4. Returns (point, alpha, beta) where
/// alpha/beta are the parameters along each segment, or None if parallel/outside.
fn seg_intersect(
  p1 : @f64.DVec2,
  p2 : @f64.DVec2,
  p3 : @f64.DVec2,
  p4 : @f64.DVec2,
) -> (@f64.DVec2, Double, Double)? {
  let r = p2 - p1
  let s = p4 - p3
  let denom = r.cross(s)
  if denom.abs() < 1.0e-12 {
    return None
  }
  let qp = p3 - p1
  let alpha = qp.cross(s) / denom
  let beta = qp.cross(r) / denom
  if alpha <= 1.0e-9 || alpha >= 1.0 - 1.0e-9 || beta <= 1.0e-9 || beta >= 1.0 - 1.0e-9 {
    return None
  }
  Some((p1 + r.scale(alpha), alpha, beta))
}

///|
/// Intersect segment p1->p2 with the infinite line through a, b (used by
/// Sutherland–Hodgman, which clips against clip-edge lines, not segments).
fn line_intersect(
  p1 : @f64.DVec2,
  p2 : @f64.DVec2,
  a : @f64.DVec2,
  b : @f64.DVec2,
) -> @f64.DVec2? {
  let r = p2 - p1
  let s = b - a
  let denom = r.cross(s)
  if denom.abs() < 1.0e-12 {
    return None
  }
  let alpha = (a - p1).cross(s) / denom
  Some(p1 + r.scale(alpha))
}

///|
/// Ray-casting point-in-polygon test (polygon implicitly closed).
pub fn point_in_polygon(pt : @f64.DVec2, poly : Array[@f64.DVec2]) -> Bool {
  let mut inside = false
  let n = poly.length()
  let mut j = n - 1
  for i = 0; i < n; i = i + 1 {
    let pi = poly[i]
    let pj = poly[j]
    if (pi.y > pt.y) != (pj.y > pt.y) {
      let xint = (pj.x - pi.x) * (pt.y - pi.y) / (pj.y - pi.y) + pi.x
      if pt.x < xint {
        inside = !inside
      }
    }
    j = i
  }
  inside
}

///|
/// Sutherland–Hodgman clipping of a subject polygon against a convex clip polygon
/// (both CCW, implicitly closed). Returns the intersection polygon.
pub fn clip_convex(
  subject : Array[@f64.DVec2],
  clip : Array[@f64.DVec2],
) -> Array[@f64.DVec2] {
  let mut output = subject
  let m = clip.length()
  for i = 0; i < m; i = i + 1 {
    let a = clip[i]
    let b = clip[(i + 1) % m]
    let edge = b - a
    let input = output
    output = []
    if input.length() == 0 {
      break
    }
    let mut prev = input[input.length() - 1]
    let mut prev_inside = edge.cross(prev - a) >= 0.0
    for k = 0; k < input.length(); k = k + 1 {
      let cur = input[k]
      let cur_inside = edge.cross(cur - a) >= 0.0
      if cur_inside {
        if !prev_inside {
          match line_intersect(prev, cur, a, b) {
            Some(p) => output.push(p)
            None => ()
          }
        }
        output.push(cur)
      } else if prev_inside {
        match line_intersect(prev, cur, a, b) {
          Some(p) => output.push(p)
          None => ()
        }
      }
      prev = cur
      prev_inside = cur_inside
    }
  }
  output
}

///|
priv struct BVertex {
  pt : @f64.DVec2
  poly : Int
  mut next : Int
  mut prev : Int
  is_intersect : Bool
  mut entry : Bool
  mut visited : Bool
  mut neighbor : Int
  alpha : Double
}

///|
fn relink(list : Array[BVertex]) -> Unit {
  let n = list.length()
  for i = 0; i < n; i = i + 1 {
    list[i].next = (i + 1) % n
    list[i].prev = (i - 1 + n) % n
  }
}

///|
/// Greiner–Hormann boolean of two simple polygons (implicitly closed, general
/// position: no shared edges/vertices). Returns the result region polygons.
pub fn boolean_polygons(
  subj : Array[@f64.DVec2],
  clip : Array[@f64.DVec2],
  op : BoolOp,
) -> Array[Array[@f64.DVec2]] {
  let n = subj.length()
  let m = clip.length()
  // Phase 1: collect intersections per original edge, then insert.
  // p_edge[i] / q_edge[j] hold (param, point, other_edge, other_param, id).
  let p_edge : Array[Array[(Double, @f64.DVec2, Int, Double, Int)]] = []
  let q_edge : Array[Array[(Double, @f64.DVec2, Int, Double, Int)]] = []
  for i = 0; i < n; i = i + 1 {
    p_edge.push([])
  }
  for j = 0; j < m; j = j + 1 {
    q_edge.push([])
  }
  let mut id = 0
  for i = 0; i < n; i = i + 1 {
    let p1 = subj[i]
    let p2 = subj[(i + 1) % n]
    for j = 0; j < m; j = j + 1 {
      let p3 = clip[j]
      let p4 = clip[(j + 1) % m]
      match seg_intersect(p1, p2, p3, p4) {
        None => ()
        Some((pt, alpha, beta)) => {
          p_edge[i].push((alpha, pt, j, beta, id))
          q_edge[j].push((beta, pt, i, alpha, id))
          id = id + 1
        }
      }
    }
  }
  // No intersections: containment decides the result.
  if id == 0 {
    let subj_in_clip = point_in_polygon(subj[0], clip)
    let clip_in_subj = point_in_polygon(clip[0], subj)
    let out : Array[Array[@f64.DVec2]] = []
    match op {
      Intersection => {
        if subj_in_clip {
          out.push(subj)
        } else if clip_in_subj {
          out.push(clip)
        }
      }
      Union => {
        if subj_in_clip {
          out.push(clip)
        } else if clip_in_subj {
          out.push(subj)
        } else {
          out.push(subj)
          out.push(clip)
        }
      }
      Difference => {
        if subj_in_clip {
          // wholly inside -> empty
        } else if clip_in_subj {
          // hole: represented as outer + reversed inner (caller handles winding)
          out.push(subj)
          let rev : Array[@f64.DVec2] = []
          for k = 0; k < m; k = k + 1 {
            rev.push(clip[m - 1 - k])
          }
          out.push(rev)
        } else {
          out.push(subj)
        }
      }
    }
    return out
  }
  // Insert intersections into augmented lists (sorted by param along each edge).
  let paug : Array[BVertex] = []
  let p_id_index : Array[Int] = [] // intersection id -> index in paug
  for k = 0; k < id; k = k + 1 {
    p_id_index.push(-1)
  }
  for i = 0; i < n; i = i + 1 {
    paug.push({
      pt: subj[i], poly: 0, next: 0, prev: 0,
      is_intersect: false, entry: false, visited: false, neighbor: -1, alpha: 0.0,
    })
    let ints = p_edge[i]
    // insertion sort by alpha
    for a = 1; a < ints.length(); a = a + 1 {
      let mut b = a
      while b > 0 && ints[b].0 < ints[b - 1].0 {
        let tmp = ints[b]
        ints[b] = ints[b - 1]
        ints[b - 1] = tmp
        b = b - 1
      }
    }
    for a = 0; a < ints.length(); a = a + 1 {
      let (alpha, pt, _, _, iid) = ints[a]
      p_id_index[iid] = paug.length()
      paug.push({
        pt, poly: 0, next: 0, prev: 0,
        is_intersect: true, entry: false, visited: false, neighbor: -1, alpha,
      })
    }
  }
  let qaug : Array[BVertex] = []
  let q_id_index : Array[Int] = []
  for k = 0; k < id; k = k + 1 {
    q_id_index.push(-1)
  }
  for j = 0; j < m; j = j + 1 {
    qaug.push({
      pt: clip[j], poly: 1, next: 0, prev: 0,
      is_intersect: false, entry: false, visited: false, neighbor: -1, alpha: 0.0,
    })
    let ints = q_edge[j]
    for a = 1; a < ints.length(); a = a + 1 {
      let mut b = a
      while b > 0 && ints[b].0 < ints[b - 1].0 {
        let tmp = ints[b]
        ints[b] = ints[b - 1]
        ints[b - 1] = tmp
        b = b - 1
      }
    }
    for a = 0; a < ints.length(); a = a + 1 {
      let (beta, pt, _, _, iid) = ints[a]
      q_id_index[iid] = qaug.length()
      qaug.push({
        pt, poly: 1, next: 0, prev: 0,
        is_intersect: true, entry: false, visited: false, neighbor: -1, alpha: beta,
      })
    }
  }
  relink(paug)
  relink(qaug)
  // Link neighbors.
  for k = 0; k < id; k = k + 1 {
    let pi = p_id_index[k]
    let qi = q_id_index[k]
    paug[pi].neighbor = qi
    qaug[qi].neighbor = pi
  }
  // Phase 2: entry/exit marking via the midpoint just before each intersection.
  for i = 0; i < paug.length(); i = i + 1 {
    if paug[i].is_intersect {
      let mid = (paug[paug[i].prev].pt + paug[i].pt).scale(0.5)
      paug[i].entry = !point_in_polygon(mid, clip)
    }
  }
  for j = 0; j < qaug.length(); j = j + 1 {
    if qaug[j].is_intersect {
      let mid = (qaug[qaug[j].prev].pt + qaug[j].pt).scale(0.5)
      qaug[j].entry = !point_in_polygon(mid, subj)
    }
  }
  // Phase 3: traversal.
  let results : Array[Array[@f64.DVec2]] = []
  for si = 0; si < paug.length(); si = si + 1 {
    if !paug[si].is_intersect || paug[si].visited {
      continue
    }
    let poly : Array[@f64.DVec2] = []
    let mut cur_poly = 0
    let mut cur_idx = si
    let start_poly = 0
    let start_idx = si
    let mut steps = 0
    while steps < 10000 {
      steps = steps + 1
      let list = if cur_poly == 0 { paug } else { qaug }
      let v = list[cur_idx]
      v.visited = true
      let other = if cur_poly == 0 { qaug } else { paug }
      other[v.neighbor].visited = true
      poly.push(v.pt)
      let forward = match op {
        Intersection => v.entry
        Union => !v.entry
        Difference => if cur_poly == 0 { !v.entry } else { v.entry }
      }
      if forward {
        cur_idx = v.next
        while !list[cur_idx].is_intersect {
          poly.push(list[cur_idx].pt)
          cur_idx = list[cur_idx].next
        }
      } else {
        cur_idx = v.prev
        while !list[cur_idx].is_intersect {
          poly.push(list[cur_idx].pt)
          cur_idx = list[cur_idx].prev
        }
      }
      let next_idx = list[cur_idx].neighbor
      cur_poly = 1 - cur_poly
      cur_idx = next_idx
      if cur_poly == start_poly && cur_idx == start_idx {
        break
      }
    }
    if poly.length() >= 3 {
      results.push(poly)
    }
  }
  results
}