///|
/// One node in the canonical `explode-offsets.json` contract. All three
/// explode mechanisms emit this value, so no plan is ever reconstructed from
/// comparing an assembled STEP against an exploded STEP.
pub struct ExplodeOffsetNode {
  /// Fully qualified node name as emitted by `to_design()`.
  name : String
  /// Declared explode displacement in millimeters.
  offset_mm : (Double, Double, Double)
  /// Assembled bounding-box center in millimeters; used for plan spans.
  assembled_center_mm : (Double, Double, Double)?
  /// Optional role color applied to this node.
  color : @step_cad.Rgb?
}

///|
/// Builds one node entry. `name` is the fully qualified node name emitted by
/// `to_design()`; `offset_mm` is its declared explode displacement. The
/// assembled center and role color are optional.
pub fn ExplodeOffsetNode::new(
  name~ : String,
  offset_mm~ : (Double, Double, Double),
  assembled_center_mm? : (Double, Double, Double),
  color? : @step_cad.Rgb,
) -> ExplodeOffsetNode {
  { name, offset_mm, assembled_center_mm, color, }
}

///|
/// The single declared output of an explode: explicit per-node offsets plus
/// the layout class that tells `check_explode.py` which geometric rules apply.
pub struct ExplodeOffsets {
  /// `coaxial` or `freeform`; selects the checker's geometric rules.
  layout : String
  /// Provenance, always `declared` for a value built by this module.
  source : String
  /// One entry per exploded design node, in node order.
  nodes : Array[ExplodeOffsetNode]
  /// Declared layers with labels, reasons, hosts and spans. Empty for layouts
  /// whose layers are derived from equal offsets by the plan builder.
  layers : Array[LayerPlacement]
}

///|
/// A collision-free coaxial stack (mechanism 1).
///
/// # Example
/// ```mbt check
/// test {
///   let o = @cad.ExplodeOffsets::coaxial([
///     @cad.ExplodeOffsetNode::new(name="a", offset_mm=(0.0, 0.0, 10.0)),
///   ])
///   inspect(o.layout, content="coaxial")
///   inspect(o.source, content="declared")
///   inspect(o.nodes.length(), content="1")
/// }
/// ```
pub fn ExplodeOffsets::coaxial(
  nodes : Array[ExplodeOffsetNode],
  layers? : Array[LayerPlacement],
) -> ExplodeOffsets {
  {
    layout: "coaxial",
    source: "declared",
    nodes,
    layers: layers.unwrap_or([]),
  }
}

///|
/// A hand-tuned radial or mate-axis explosion (mechanisms 2 and 3).
///
/// # Example
/// ```mbt check
/// test {
///   let o = @cad.ExplodeOffsets::freeform([
///     @cad.ExplodeOffsetNode::new(name="screw", offset_mm=(24.0, 0.0, 475.0)),
///   ])
///   inspect(o.layout, content="freeform")
///   inspect(o.to_json().contains("explode-offsets@1"), content="true")
/// }
/// ```
pub fn ExplodeOffsets::freeform(
  nodes : Array[ExplodeOffsetNode],
  layers? : Array[LayerPlacement],
) -> ExplodeOffsets {
  {
    layout: "freeform",
    source: "declared",
    nodes,
    layers: layers.unwrap_or([]),
  }
}

///|
fn offsets_json_object(entries : Array[(String, @json.Json)]) -> @json.Json {
  let map : Map[String, @json.Json] = Map([])
  for entry in entries {
    map.set(entry.0, entry.1)
  }
  @json.Json::object(map)
}

///|
fn offsets_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 offset_node_json(n : ExplodeOffsetNode) -> @json.Json {
  let center = match n.assembled_center_mm {
    Some(c) => offsets_json_vec3(c)
    None => @json.Json::null()
  }
  let color = match n.color {
    Some(c) => offsets_json_vec3(c.channels())
    None => @json.Json::null()
  }
  offsets_json_object([
    ("name", @json.Json::string(n.name)),
    ("offset_mm", offsets_json_vec3(n.offset_mm)),
    ("assembled_center_mm", center),
    ("color", color),
  ])
}

///|
fn offset_is_finite(v : Double) -> Bool {
  // NaN is the only value that is not equal to itself.
  v == v && v.abs() < 1.0e30
}

///|
/// Returns the problems that would make this offsets document invalid. Mirrors
/// `scripts/explode_offsets.py::validate` so a malformed document is caught at
/// the point of writing rather than downstream.
pub fn ExplodeOffsets::validate(self : ExplodeOffsets) -> Array[String] {
  let problems : Array[String] = []
  if self.nodes.length() == 0 {
    problems.push("no nodes")
  }
  if self.layout != "coaxial" && self.layout != "freeform" {
    problems.push("invalid layout: " + self.layout)
  }
  if self.source == "" {
    problems.push("empty source")
  }
  for node in self.nodes {
    let (x, y, z) = node.offset_mm
    if !offset_is_finite(x) || !offset_is_finite(y) || !offset_is_finite(z) {
      problems.push("non-finite offset for " + node.name)
    }
    match node.assembled_center_mm {
      Some((cx, cy, cz)) =>
        if !offset_is_finite(cx) ||
          !offset_is_finite(cy) ||
          !offset_is_finite(cz) {
          problems.push("non-finite center for " + node.name)
        }
      None => ()
    }
  }
  problems
}

///|
/// Serializes the canonical offsets document consumed by
/// `scripts/explode_offsets.py`. Raises `ExplodeError` rather than emitting a
/// document that the plan tooling would reject.
pub fn ExplodeOffsets::to_json(
  self : ExplodeOffsets,
) -> String raise ExplodeError {
  let problems = self.validate()
  if problems.length() > 0 {
    let mut msg = "invalid explode offsets:"
    for problem in problems {
      msg = msg + "\n  " + problem
    }
    raise ExplodeError(msg)
  }
  offsets_json_object([
    ("schema", @json.Json::string("gmlewis/cad/explode-offsets@1")),
    ("layout", @json.Json::string(self.layout)),
    ("source", @json.Json::string(self.source)),
    ("nodes", @json.Json::array(self.nodes.map(offset_node_json))),
    ("layers", @json.Json::array(self.layers.map(placement_json))),
  ]).stringify()
}