///|
/// Declarative coaxial `ExplodeStack` builder for collision-free exploded views.
///
/// Replaces hand-written `if name.contains(...)` chains with a readable stack
/// of `ExplodeLayer` values that automatically computes non-overlapping
/// Z offsets from each layer's real assembled bounding box:
///
/// ```mbt nocheck
/// let exploded = ExplodeStack::z_axis(anchor="ACT-HOUSING", gap_mm=18.0)
///   .group(ExplodeLayer::new(label="gear train", patterns=["gearbox", "bearing-688"]).with_reason("lift off housing"))
///   .group(ExplodeLayer::new(label="output", patterns=["output_cover", "output_flange"]))
///   .group(ExplodeLayer::new(label="motor", patterns=["motor", "rotor_adapter"]).with_side(Below))
///   .group(ExplodeLayer::new(label="controller", patterns=["moteus"]).with_side(Below))
///   .apply(assembled_design)
/// ```
///
/// ## Which explode mechanism to use
///
/// Use `ExplodeStack` when a design separates into coaxial layers around a
/// stationary anchor and you want strict classification, collision-free
/// spacing, labels, reasons, host assertions and a generated plan. Use typed
/// `ExplodeSpec` attachments when the offsets follow mate axes and should
/// propagate down a joint tree. The wheel/gearbox family uses a deliberate
/// hand-tuned radial layout (`gearbox_exploded_design()`) for fixed tiers and
/// per-node radial fan-out that a coaxial stack cannot express. All three emit
/// the same `ExplodeOffsets` contract.
///
/// `group()` takes exactly one `ExplodeLayer`. Build it with
/// `ExplodeLayer::new(label~, patterns~)` and declare options fluently:
/// `with_side`, `with_match_mode` (or `exact`/`glob`), `with_predicate`,
/// `with_slide`, `with_color`, `with_host`, `with_reason`, `with_gap`.
/// `offsets()` and `apply()` are strict — they raise `ExplodeError` on
/// unclassified nodes, empty layers or a broken host assertion; use
/// `allow_unmatched()` for intentionally stationary parts and
/// `diagnostics()`/`placements()`/`describe()`/`plan_json()` to introspect
/// without raising.

///|
/// Which side of the anchor a layer explodes toward.
pub(all) enum ExplodeSide {
  /// Above the anchor, in the `+Z` direction.
  Above
  /// Below the anchor, in the `-Z` direction.
  Below
}

///|
/// How a layer's patterns are compared against a `SceneNode` name.
pub(all) enum MatchMode {
  /// Substring match. Historical default; a short name can swallow a longer one.
  Contains
  /// Exact equality with the fully qualified node name.
  Exact
  /// Shell-style glob where `*` matches any run of characters.
  Glob
}

///|
/// One layer in an `ExplodeStack`: a fluent value built with `new` and `with_*`.
/// Layers match any node whose name satisfies `match_mode` against at least one
/// of `patterns` (and `predicate` when set).
///
/// This is a domain value, not an options struct used to bundle function
/// arguments: the same value is consumed by `placements()`, `diagnostics()`
/// and `plan_json()`, so labels, reasons, hosts and colors live on the layer
/// itself and are reported in the generated plan.
pub struct ExplodeLayer {
  patterns : Array[String]
  gap_override_mm : Double?
  predicate : ((@step_cad.SceneNode) -> Bool)?
  match_mode : MatchMode
  /// Short human name for this layer, used by `describe()` and `plan_json()`.
  label : String
  /// Why this layer sits where it does; emitted by `describe()`.
  reason : String
  /// Extra translation applied to every node in the layer, in millimeters.
  slide_mm : (Double, Double, Double)
  /// Optional role color applied by `apply()`.
  color : @step_cad.Rgb?
  /// Name of the layer this fastener group clamps. A validated assertion.
  host : String?
  /// Which side of the anchor this layer explodes toward.
  side : ExplodeSide
}

///|
/// Starts a layer: a short `label` and the `patterns` that select its nodes.
/// Everything else defaults; declare options with the `with_*` methods.
///
/// # Example
/// ```mbt check
/// test {
///   let l = @cad.ExplodeLayer::new(label="fan", patterns=["krc_cover_fan"])
///   inspect(l.label, content="fan")
/// }
/// ```
pub fn ExplodeLayer::new(
  label~ : String,
  patterns~ : Array[String],
) -> ExplodeLayer {
  {
    patterns,
    gap_override_mm: None,
    predicate: None,
    match_mode: Contains,
    label,
    reason: "",
    slide_mm: (0.0, 0.0, 0.0),
    color: None,
    host: None,
    side: Above,
  }
}

///|
/// Compares node names with `match_mode` (see also `exact`/`glob`).
pub fn ExplodeLayer::with_match_mode(
  self : ExplodeLayer,
  mode : MatchMode,
) -> ExplodeLayer {
  { ..self, match_mode: mode, }
}

///|
/// Matches node names exactly, so a short name cannot swallow a longer one.
pub fn ExplodeLayer::exact(self : ExplodeLayer) -> ExplodeLayer {
  self.with_match_mode(Exact)
}

///|
/// Matches node names with a shell-style `*` glob.
pub fn ExplodeLayer::glob(self : ExplodeLayer) -> ExplodeLayer {
  self.with_match_mode(Glob)
}

///|
/// Filters nodes that share a pattern (e.g. upper vs. lower inserts).
pub fn ExplodeLayer::with_predicate(
  self : ExplodeLayer,
  predicate : (@step_cad.SceneNode) -> Bool,
) -> ExplodeLayer {
  { ..self, predicate: Some(predicate), }
}

///|
/// Why this layer sits where it does; emitted by `describe()`.
pub fn ExplodeLayer::with_reason(
  self : ExplodeLayer,
  reason : String,
) -> ExplodeLayer {
  { ..self, reason, }
}

///|
/// The part this fastener group clamps; `diagnostics()` validates it.
pub fn ExplodeLayer::with_host(
  self : ExplodeLayer,
  host : String,
) -> ExplodeLayer {
  { ..self, host: Some(host), }
}

///|
/// Applies a role color to every node in the layer via `apply()`.
pub fn ExplodeLayer::with_color(
  self : ExplodeLayer,
  color : @step_cad.Rgb,
) -> ExplodeLayer {
  { ..self, color: Some(color), }
}

///|
/// Slides the whole subassembly off the main axis, in millimeters.
pub fn ExplodeLayer::with_slide(
  self : ExplodeLayer,
  slide_mm : (Double, Double, Double),
) -> ExplodeLayer {
  { ..self, slide_mm, }
}

///|
/// Overrides the stack's default inter-layer gap for this layer only.
pub fn ExplodeLayer::with_gap(
  self : ExplodeLayer,
  gap_mm : Double,
) -> ExplodeLayer {
  { ..self, gap_override_mm: Some(gap_mm), }
}

///|
/// Puts the layer below the anchor (`-Z`) instead of above (`+Z`).
pub fn ExplodeLayer::with_side(
  self : ExplodeLayer,
  side : ExplodeSide,
) -> ExplodeLayer {
  { ..self, side, }
}

///|
/// Declarative Z-axis explode layout anchored at one or more stationary parts,
/// with ordered layers exploding in `+Z` (above) and `-Z` (below) directions.
pub struct ExplodeStack {
  anchor_patterns : Array[String]
  above_layers : Array[ExplodeLayer]
  below_layers : Array[ExplodeLayer]
  default_gap_mm : Double
  /// Node substrings explicitly allowed to remain unclassified.
  allowed_unmatched : Array[String]
}

///|
/// Starts a Z-axis coaxial `ExplodeStack` anchored on parts whose name contains
/// `anchor`, with default inter-layer clearance `gap_mm`.
pub fn ExplodeStack::z_axis(
  anchor~ : String,
  gap_mm~ : Double = 20.0,
) -> ExplodeStack {
  {
    anchor_patterns: [anchor],
    above_layers: [],
    below_layers: [],
    default_gap_mm: gap_mm,
    allowed_unmatched: [],
  }
}

///|
/// Adds an additional stationary anchor substring to this stack.
pub fn ExplodeStack::with_anchor(
  self : ExplodeStack,
  pattern : String,
) -> ExplodeStack {
  let anchors = self.anchor_patterns.copy()
  anchors.push(pattern)
  { ..self, anchor_patterns: anchors, }
}

///|
/// Marks node substrings that are intentionally left in the assembled position.
/// `diagnostics()` no longer reports them, but they still receive a zero offset.
pub fn ExplodeStack::allow_unmatched(
  self : ExplodeStack,
  patterns : Array[String],
) -> ExplodeStack {
  let allowed = self.allowed_unmatched.copy()
  for pat in patterns {
    allowed.push(pat)
  }
  { ..self, allowed_unmatched: allowed, }
}

///|
fn ExplodeStack::push_above(
  self : ExplodeStack,
  layer : ExplodeLayer,
) -> ExplodeStack {
  let layers = self.above_layers.copy()
  layers.push(layer)
  { ..self, above_layers: layers, }
}

///|
fn ExplodeStack::push_below(
  self : ExplodeStack,
  layer : ExplodeLayer,
) -> ExplodeStack {
  let layers = self.below_layers.copy()
  layers.push(layer)
  { ..self, below_layers: layers, }
}

///|
/// Appends one declared layer — the single way to build an exploded stack.
/// The layer value carries its own match mode, side, slide, color, host and
/// reason, so `group()` needs exactly that one argument.
///
/// # Example
/// ```mbt check
/// test {
///   let d = @step_cad.Design::new(name="es")
///     .add(@step_cad.Cylinder::new(10.0, 5.0).with_name("base").translate(z=0.0))
///     .add(
///       @step_cad.Cylinder::new(8.0, 4.0).with_name("bearing").translate(z=7.0),
///     )
///   let s = @cad.ExplodeStack::z_axis(anchor="base", gap_mm=10.0).group(
///     @cad.ExplodeLayer::new(label="bearing", patterns=["bearing"]),
///   )
///   inspect(s.diagnostics(d).is_ok(), content="true")
/// }
/// ```
pub fn ExplodeStack::group(
  self : ExplodeStack,
  layer : ExplodeLayer,
) -> ExplodeStack {
  match layer.side {
    Above => self.push_above(layer)
    Below => self.push_below(layer)
  }
}

///|
/// A node's Z extent in the assembled design, in millimeters.
fn z_span(node : @step_cad.SceneNode) -> (Double, Double) {
  let (_, _, _, _, z0, z1) = node.bounding_box()
  (z0, z1)
}

///|
/// Finds `needle` in `hay` at or after `start`, returning its byte offset.
fn find_from(hay : String, needle : String, start : Int32) -> Int32? {
  let h = hay.length()
  let n = needle.length()
  for i = start; i + n <= h; {
    if String::unsafe_substring(hay, start=i, end=i + n) == needle {
      break Some(i)
    }
    continue i + 1
  } nobreak {
    None
  }
}

///|
/// Shell-style glob with `*` as the only metacharacter.
fn glob_match(pattern : String, name : String) -> Bool {
  let parts : Array[String] = []
  for view in pattern.split("*") {
    parts.push(view.to_owned())
  }
  let leading_star = parts.length() > 0 && parts[0] == ""
  let trailing_star = parts.length() > 0 && parts[parts.length() - 1] == ""
  for part in parts; pos = 0 {
    if part == "" {
      continue pos
    }
    match find_from(name, part, pos) {
      Some(i) => {
        if pos == 0 && !leading_star && i != 0 {
          break false
        }
        continue i + part.length()
      }
      None => break false
    }
  } nobreak {
    trailing_star || pos == name.length()
  }
}

///|
fn pattern_matches(mode : MatchMode, pattern : String, name : String) -> Bool {
  match mode {
    Contains => name.contains(pattern)
    Exact => name == pattern
    Glob => glob_match(pattern, name)
  }
}

///|
fn layer_matches(layer : ExplodeLayer, node : @step_cad.SceneNode) -> Bool {
  let mut name_ok = false
  for pat in layer.patterns {
    if pattern_matches(layer.match_mode, pat, node.name) {
      name_ok = true
      break
    }
  }
  if !name_ok {
    return false
  }
  match layer.predicate {
    Some(pred) => pred(node)
    None => true
  }
}

///|
fn z_vector(offset : Double) -> (Double, Double, Double) {
  (0.0, 0.0, offset)
}

///|
fn add_vec(
  a : (Double, Double, Double),
  b : (Double, Double, Double),
) -> (Double, Double, Double) {
  (a.0 + b.0, a.1 + b.1, a.2 + b.2)
}

///|
fn slide_z(slide : (Double, Double, Double)) -> Double {
  slide.2
}

///|
/// Computed geometry for one declared layer.
priv struct LayerComputation {
  side : Int32
  index : Int32
  layer : ExplodeLayer
  has : Bool
  min_mm : Double
  max_mm : Double
  names : Array[String]
  scalar_off : Double
  final_min_mm : Double
  final_max_mm : Double
}

///|
/// The single classification + offset pass shared by `offsets()`,
/// `placements()`, `diagnostics()`, `describe()` and `plan_json()`.
priv struct ExplodeComputation {
  above : Array[LayerComputation]
  below : Array[LayerComputation]
  buckets : Array[Int32]
  is_anchor : Array[Bool]
  anchor_names : Array[String]
  anchor_min : Double
  anchor_max : Double
}

///|
fn ExplodeStack::compute(
  self : ExplodeStack,
  design : @step_cad.Design,
) -> ExplodeComputation {
  let n_above = self.above_layers.length()
  let n_below = self.below_layers.length()
  let above_has : Array[Bool] = Array::make(n_above, false)
  let above_min : Array[Double] = Array::make(n_above, 0.0)
  let above_max : Array[Double] = Array::make(n_above, 0.0)
  let below_has : Array[Bool] = Array::make(n_below, false)
  let below_min : Array[Double] = Array::make(n_below, 0.0)
  let below_max : Array[Double] = Array::make(n_below, 0.0)
  let above_names : Array[Array[String]] = []
  let below_names : Array[Array[String]] = []
  for _ in 0.. anchor_max {
          anchor_max = hi
        }
      }
      continue
    }
    is_anchor.push(false)
    let mut matched = 0
    for k in 0.. above_max[k] {
            above_max[k] = hi
          }
        }
        above_names[k].push(node.name)
        break
      }
    }
    if matched == 0 {
      for k in 0.. below_max[k] {
              below_max[k] = hi
            }
          }
          below_names[k].push(node.name)
          break
        }
      }
    }
    buckets.push(matched)
  }

  // Above: walk upward from the anchor's top, spacing each layer by its gap.
  let above_off : Array[Double] = Array::make(n_above, 0.0)
  let above_final_min : Array[Double] = Array::make(n_above, 0.0)
  let above_final_max : Array[Double] = Array::make(n_above, 0.0)
  let mut cursor_up = anchor_max
  for k in 0.. 0.0 { delta } else { 0.0 }
    above_off[k] = off
    let shift = off + slide_z(self.above_layers[k].slide_mm)
    above_final_min[k] = above_min[k] + shift
    above_final_max[k] = above_max[k] + shift
    cursor_up = above_final_max[k]
  }

  // Below: walk downward from the anchor's bottom.
  let below_off : Array[Double] = Array::make(n_below, 0.0)
  let below_final_min : Array[Double] = Array::make(n_below, 0.0)
  let below_final_max : Array[Double] = Array::make(n_below, 0.0)
  let mut cursor_dn = anchor_min
  for k in 0.. (Double, Double, Double) {
  add_vec(z_vector(comp.scalar_off), comp.layer.slide_mm)
}

///|
/// Computes collision-free `(dx, dy, dz)` explode offsets (mm) for every node
/// in `design` (in the same order as `design.nodes()`).
///
/// Strict by default: raises `ExplodeError` when `diagnostics()` finds
/// unclassified nodes, empty layers, a broken host assertion, overlapping
/// spans, or an undocumented slide. Use `allow_unmatched()` to declare
/// intentionally stationary nodes, or `placements()` / `plan_json()` for
/// introspection that must not raise.
pub fn ExplodeStack::offsets(
  self : ExplodeStack,
  design : @step_cad.Design,
) -> Array[(String, (Double, Double, Double))] raise ExplodeError {
  let diag = self.diagnostics(design)
  if !diag.is_ok() {
    raise ExplodeError(diagnostics_message(diag))
  }
  self.offsets_unchecked(design)
}

///|
/// Computes offsets without validating. Used by `offsets()` after its check
/// and by `apply()` after its own check; not part of the public API.
fn ExplodeStack::offsets_unchecked(
  self : ExplodeStack,
  design : @step_cad.Design,
) -> Array[(String, (Double, Double, Double))] {
  let comp = self.compute(design)
  let nodes = design.nodes()
  let out : Array[(String, (Double, Double, Double))] = []
  for i in 0.. 0 {
      layer_offset(comp.above[bucket - 1])
    } else if bucket < 0 {
      layer_offset(comp.below[-bucket - 1])
    } else {
      (0.0, 0.0, 0.0)
    }
    out.push((nodes[i].name, vector))
  }
  out
}

///|
/// One declared layer's final placement, in millimeters.
pub struct LayerPlacement {
  index : Int32
  side : Int32
  label : String
  reason : String
  matched_names : Array[String]
  assembled_span_mm : (Double, Double)
  final_span_mm : (Double, Double)
  offset_mm : (Double, Double, Double)
  declared_gap_mm : Double
  host : String?
  slide_mm : (Double, Double, Double)
  color : @step_cad.Rgb?
}

///|
fn to_placement(
  default_gap : Double,
  comp : LayerComputation,
) -> LayerPlacement {
  {
    index: comp.index,
    side: comp.side,
    label: comp.layer.label,
    reason: comp.layer.reason,
    matched_names: comp.names.copy(),
    assembled_span_mm: (comp.min_mm, comp.max_mm),
    final_span_mm: (comp.final_min_mm, comp.final_max_mm),
    offset_mm: layer_offset(comp),
    declared_gap_mm: comp.layer.gap_override_mm.unwrap_or(default_gap),
    host: comp.layer.host,
    slide_mm: comp.layer.slide_mm,
    color: comp.layer.color,
  }
}

///|
/// Every declared layer's computed placement, in stack order (below layers
/// first, then above layers). Unlike `offsets()`, these are final world-space
/// spans in millimeters, not deltas, so sorting them is meaningful.
pub fn ExplodeStack::placements(
  self : ExplodeStack,
  design : @step_cad.Design,
) -> Array[LayerPlacement] {
  let comp = self.compute(design)
  let out : Array[LayerPlacement] = []
  let mut b = comp.below.length()
  while b > 0 {
    b -= 1
    out.push(to_placement(self.default_gap_mm, comp.below[b]))
  }
  for k in 0.. Bool {
  self.unmatched.length() == 0 &&
  self.empty_layers.length() == 0 &&
  self.host_violations.length() == 0 &&
  self.overlapped_layers.length() == 0 &&
  self.out_of_order.length() == 0 &&
  self.slide_undeclared.length() == 0
}

///|
fn layer_name(comp : LayerComputation) -> String {
  if comp.layer.label != "" {
    comp.layer.label
  } else if comp.layer.patterns.length() > 0 {
    comp.layer.patterns[0]
  } else {
    "layer \{comp.index}"
  }
}

///|
/// Finds `Contains` patterns that are a strict prefix of a later layer's
/// pattern. Layers are matched in declaration order, so the earlier substring
/// can swallow the later layer's nodes — the oldest exploded-view footgun. A
/// `predicate~` on the earlier layer means the author already discriminates,
/// so those layers are not reported.
fn find_prefix_collisions(
  above : Array[LayerComputation],
  below : Array[LayerComputation],
) -> Array[(String, String, String)] {
  let ordered : Array[LayerComputation] = []
  for c in above {
    ordered.push(c)
  }
  for c in below {
    ordered.push(c)
  }
  let out : Array[(String, String, String)] = []
  for i in 0.. true
      None => false
    }
    if !has_pred {
      if a.layer.match_mode is Contains {
        for pa in a.layer.patterns {
          for j in (i + 1).. Bool {
  let mut allowed = false
  for pat in self.allowed_unmatched {
    if name.contains(pat) {
      allowed = true
      break
    }
  }
  allowed
}

///|
/// Verifies the stack against a design without raising. `offsets()` keeps its
/// Historical silent behavior is gone; `offsets()` now fails loudly.
pub fn ExplodeStack::diagnostics(
  self : ExplodeStack,
  design : @step_cad.Design,
) -> ExplodeDiagnostics {
  let comp = self.compute(design)
  let nodes = design.nodes()
  let unmatched : Array[String] = []
  for i in 0.. 0 {
    b -= 1
    ordered.push(comp.below[b])
  }
  for c in comp.above {
    ordered.push(c)
  }

  let overlapped_layers : Array[(Int32, Int32, Double)] = []
  let out_of_order : Array[(Int32, Int32)] = []
  let host_violations : Array[HostViolation] = []
  for k in 0.. 0 {
      j -= 1
      if ordered[j].has {
        prev = Some(ordered[j])
        break
      }
    }
    match prev {
      Some(p) => {
        if cur.final_min_mm + 1.0e-6 < p.final_max_mm {
          overlapped_layers.push(
            (p.index, cur.index, p.final_max_mm - cur.final_min_mm),
          )
        }
        if cur.final_min_mm + 1.0e-6 < p.final_min_mm {
          out_of_order.push((p.index, cur.index))
        }
      }
      None => ()
    }
    match cur.layer.host {
      Some(host) => {
        // The host may be the anchor, a lower layer, this layer (a fastener
        // traveling with its host), or a higher layer (a bolt hanging from a
        // top part). It must exist; when it sits lower, this layer must be
        // above it. That catches typos and fasteners on the wrong side.
        let mut found = false
        let mut above_host = false
        for n in comp.anchor_names {
          if n.contains(host) {
            found = true
            above_host = cur.final_min_mm + 1.0e-6 >= comp.anchor_max
            break
          }
        }
        if !found {
          let mut h = k
          while true {
            for n in ordered[h].names {
              if n.contains(host) {
                found = true
                above_host = h == k ||
                  cur.final_min_mm + 1.0e-6 >= ordered[h].final_max_mm
                break
              }
            }
            if found || h == 0 {
              break
            }
            h -= 1
          }
        }
        // Finally allow a host that only exists in a higher layer.
        if !found {
          for j in (k + 1).. ()
    }
  }

  {
    unmatched,
    empty_layers,
    host_violations,
    overlapped_layers,
    out_of_order,
    slide_undeclared,
    prefix_collisions,
  }
}

///|
/// The strict `offsets()` refuses a stack with classification or host errors.
pub suberror ExplodeError {
  ExplodeError(String)
}

///|
pub impl Show for ExplodeError with fn output(self, logger) {
  let ExplodeError(msg) = self
  logger.write_string(msg)
}

///|
fn diagnostics_message(diag : ExplodeDiagnostics) -> String {
  let mut msg = "explode stack diagnostics:"
  for n in diag.unmatched {
    msg = msg + "\n  unmatched node: " + n
  }
  for (idx, label) in diag.empty_layers {
    msg = msg + "\n  empty layer \{idx}: " + label
  }
  for v in diag.host_violations {
    msg = msg + "\n  host violation in '" + v.label + "': " + v.message
  }
  for (a, b, depth) in diag.overlapped_layers {
    msg = msg + "\n  overlapping layers \{a}/\{b} by \{depth} mm"
  }
  for (a, b) in diag.out_of_order {
    msg = msg + "\n  out-of-order layers \{a}/\{b}"
  }
  for label in diag.slide_undeclared {
    msg = msg + "\n  slide without a group label: " + label
  }
  for (layer, pattern, shadowed) in diag.prefix_collisions {
    msg = msg +
      "\n  prefix collision: '" +
      layer +
      "' pattern '" +
      pattern +
      "' can shadow '" +
      shadowed +
      "'; use exact()/glob() or declare the specific pattern first"
  }
  msg
}

///|
fn fmt_mm(v : Double) -> String {
  "\{(v * 10.0).round() / 10.0}"
}

///|
fn span_text(span : (Double, Double)) -> String {
  fmt_mm(span.0) + " .. " + fmt_mm(span.1)
}

///|
/// Renders the layer plan as Markdown from `placements()`. Generated prose
/// belongs in `build//explode-plan.md`, not in committed README files.
pub fn ExplodeStack::describe(
  self : ExplodeStack,
  design : @step_cad.Design,
) -> String {
  let ps = self.placements(design)
  let mut out = "| # | Layer | Parts | Offset (x,y,z) mm | Assembled Z (mm) | Final Z (mm) | Gap (mm) |\n"
  out = out + "| --- | --- | --- | --- | --- | --- | --- |\n"
  for k in 0.. @json.Json {
  let map : Map[String, @json.Json] = Map([])
  for entry in entries {
    map.set(entry.0, entry.1)
  }
  @json.Json::object(map)
}

///|
fn json_vec3(v : (Double, Double, Double)) -> @json.Json {
  @json.Json::array([
    @json.Json::number(v.0),
    @json.Json::number(v.1),
    @json.Json::number(v.2),
  ])
}

///|
fn json_span(v : (Double, Double)) -> @json.Json {
  @json.Json::array([@json.Json::number(v.0), @json.Json::number(v.1)])
}

///|
fn json_strings(v : Array[String]) -> @json.Json {
  @json.Json::array(v.map(fn(s) { @json.Json::string(s) }))
}

///|
fn placement_json(p : LayerPlacement) -> @json.Json {
  let host = match p.host {
    Some(h) => @json.Json::string(h)
    None => @json.Json::null()
  }
  let color = match p.color {
    Some(c) => json_vec3(c.channels())
    None => @json.Json::null()
  }
  json_object([
    ("index", @json.Json::number(p.index.to_double())),
    ("side", @json.Json::number(p.side.to_double())),
    ("label", @json.Json::string(p.label)),
    ("reason", @json.Json::string(p.reason)),
    ("matched_names", json_strings(p.matched_names)),
    ("assembled_span_mm", json_span(p.assembled_span_mm)),
    ("final_span_mm", json_span(p.final_span_mm)),
    ("offset_mm", json_vec3(p.offset_mm)),
    ("declared_gap_mm", @json.Json::number(p.declared_gap_mm)),
    ("host", host),
    ("slide_mm", json_vec3(p.slide_mm)),
    ("color", color),
  ])
}

///|
/// Machine-readable layer plan in millimeters, consumed by
/// `scripts/check_explode.py` and `scripts/explode_strip.py`.
pub fn ExplodeStack::plan_json(
  self : ExplodeStack,
  design : @step_cad.Design,
  example~ : String = "",
) -> String {
  let comp = self.compute(design)
  let diag = self.diagnostics(design)
  let ps = self.placements(design)
  json_object([
    ("schema", @json.Json::string("gmlewis/cad/explode-plan@1")),
    ("example", @json.Json::string(example)),
    ("axis", @json.Json::string("z")),
    ("layout", @json.Json::string("coaxial")),
    ("source", @json.Json::string("stack")),
    ("gap_mm", @json.Json::number(self.default_gap_mm)),
    ("anchor_names", json_strings(comp.anchor_names)),
    ("anchor_assembled_span_mm", json_span((comp.anchor_min, comp.anchor_max))),
    ("layers", @json.Json::array(ps.map(placement_json))),
    ("unmatched", json_strings(diag.unmatched)),
    (
      "empty_layers",
      @json.Json::array(
        diag.empty_layers.map(fn(e) {
          json_object([
            ("index", @json.Json::number(e.0.to_double())),
            ("label", @json.Json::string(e.1)),
          ])
        }),
      ),
    ),
    (
      "host_violations",
      @json.Json::array(
        diag.host_violations.map(fn(v) {
          json_object([
            ("layer_index", @json.Json::number(v.layer_index.to_double())),
            ("label", @json.Json::string(v.label)),
            ("host", @json.Json::string(v.host)),
            ("message", @json.Json::string(v.message)),
          ])
        }),
      ),
    ),
    (
      "overlapped_layers",
      @json.Json::array(
        diag.overlapped_layers.map(fn(o) {
          json_vec3((o.0.to_double(), o.1.to_double(), o.2))
        }),
      ),
    ),
    (
      "out_of_order",
      @json.Json::array(
        diag.out_of_order.map(fn(o) {
          @json.Json::array([
            @json.Json::number(o.0.to_double()),
            @json.Json::number(o.1.to_double()),
          ])
        }),
      ),
    ),
    ("slide_undeclared", json_strings(diag.slide_undeclared)),
    (
      "prefix_collisions",
      @json.Json::array(
        diag.prefix_collisions.map(fn(e) {
          @json.Json::array([
            @json.Json::string(e.0),
            @json.Json::string(e.1),
            @json.Json::string(e.2),
          ])
        }),
      ),
    ),
  ]).stringify()
}

///|
/// Returns a new `@step_cad.Design` with every matched node translated by its
/// collision-free coaxial explode offset, slide, and optional role color.
/// Strict by default, like `offsets()`: raises `ExplodeError` on a malformed
/// stack. Use `allow_unmatched()` for intentionally stationary nodes.
pub fn ExplodeStack::apply(
  self : ExplodeStack,
  design : @step_cad.Design,
) -> @step_cad.Design raise ExplodeError {
  let diag = self.diagnostics(design)
  if !diag.is_ok() {
    raise ExplodeError(diagnostics_message(diag))
  }
  let comp = self.compute(design)
  let nodes = design.nodes()
  let mut out = @step_cad.Design::new(
    name=design.name,
    description=design.description,
    documentation=design.documentation,
  )
  for i in 0.. 0 {
      layer_offset(comp.above[bucket - 1])
    } else if bucket < 0 {
      layer_offset(comp.below[-bucket - 1])
    } else {
      (0.0, 0.0, 0.0)
    }
    let color = if bucket > 0 {
      comp.above[bucket - 1].layer.color
    } else if bucket < 0 {
      comp.below[-bucket - 1].layer.color
    } else {
      None
    }
    let node = match color {
      Some(c) => nodes[i].with_color(c)
      None => nodes[i]
    }
    out = out.add(node.translate(x=vector.0, y=vector.1, z=vector.2))
  }
  out
}

///|
/// Canonical declared offsets for this stack. One entry per design node with
/// its exact offset, role color and assembled center; `coaxial` because
/// `offsets()` spaces layers collision-free along Z. Strict like `offsets()`.
pub fn ExplodeStack::to_offsets(
  self : ExplodeStack,
  design : @step_cad.Design,
) -> ExplodeOffsets raise ExplodeError {
  let comp = self.compute(design)
  let offsets = self.offsets(design)
  let nodes = design.nodes()
  let out : Array[ExplodeOffsetNode] = []
  for i in 0.. 0 {
      comp.above[bucket - 1].layer.color
    } else if bucket < 0 {
      comp.below[-bucket - 1].layer.color
    } else {
      None
    }
    let (x0, x1, y0, y1, z0, z1) = nodes[i].bounding_box()
    let center = ((x0 + x1) / 2.0, (y0 + y1) / 2.0, (z0 + z1) / 2.0)
    let node = match color {
      Some(c) =>
        ExplodeOffsetNode::new(
          name=nodes[i].name,
          offset_mm=offsets[i].1,
          assembled_center_mm=center,
          color=c,
        )
      None =>
        ExplodeOffsetNode::new(
          name=nodes[i].name,
          offset_mm=offsets[i].1,
          assembled_center_mm=center,
        )
    }
    out.push(node)
  }
  ExplodeOffsets::coaxial(out, layers=self.placements(design))
}