///|
/// One placed solid of a compiled component, measured in the assembled
/// (world) frame.
pub(all) struct BodyAudit {
  /// Link name of the compiled robot that owns the body.
  link : String
  /// Body name within its link.
  body : String
  /// Part number carrying the body, or an empty string when it has none.
  part_number : String
  /// Lowest corner of the axis-aligned bounding box, in millimetres.
  min : (Double, Double, Double)
  /// Highest corner of the axis-aligned bounding box, in millimetres.
  max : (Double, Double, Double)
  /// Mass from the body's inertial, in kilograms.
  mass_kg : Double
  /// Mass of the body's shape at the body's density, measured from the
  /// shape itself rather than its bounding box (a curved segment such as a
  /// rotor magnet has a box far larger than its material); zero when the
  /// volume cannot be measured, which skips the inertial check.
  solid_mass_kg : Double
}

///|
/// A finished check: the text to print and how many problems it found.
pub(all) struct CheckReport {
  /// Human-readable report, one finding per line after any tables.
  text : String
  /// Findings that make the design wrong as modeled.
  errors : Int32
  /// Findings worth a look that may be intended.
  warnings : Int32
}

///|
/// Smallest allowed ratio of inertial mass to measured shape mass before a
/// body's inertial is reported as a stale placeholder.
pub const AuditMinInertiaRatio : Double = 0.05

///|
/// Ratio of inertial mass to measured shape mass above which the audit
/// advises (advisory only, because mesh volume reads low for small parts).
pub const AuditMaxInertiaRatio : Double = 1.02

///|
/// Bounding-box gap, in millimetres, below which two bodies count as
/// touching for the support check.
pub const AuditContactGapMm : Double = 0.02

///|
/// Component::audit_bodies lists every body of every compiled link with its
/// world-frame bounding box and mass at the given joint positions.
pub fn Component::audit_bodies(
  self : Component,
  joint_positions~ : Map[String, Double] = Map([]),
) -> Array[BodyAudit] {
  let (links, joints, transmissions) = self.compile_links()
  let robot = robot_from_compiled(self, links, joints, transmissions)
  let fk = robot.forward_kinematics(joint_positions~)

  //
  let out : Array[BodyAudit] = []

  //
  for link in links {
    let world_xform = fk.get(link.name).unwrap_or(@urdf.Transform::identity())

    //
    for body in link.bodies {
      let placed = transform_scene_node_urdf(body.node, world_xform)
      let (x0, x1, y0, y1, z0, z1) = placed.bounding_box()

      //
      // Shape volume in mm^3, or zero when it cannot be measured.
      let volume_mm3 = match placed.shape.analysis_volume() {
        Ok(volume) => volume
        Err(_) => 0.0
      }
      out.push({
        link: link.name,
        body: body.node.name,
        part_number: match body.part {
          Some(meta) => meta.part_number
          None => ""
        },
        min: (x0, y0, z0),
        max: (x1, y1, z1),
        mass_kg: body.inertial.mass,
        solid_mass_kg: volume_mm3 * 1.0e-9 * body.density.to_kg_per_m3(),
      })
    }
  }

  //
  out
}

///|
/// audit_num formats a millimetre value with exactly one decimal, without
/// padding.
fn audit_num(value : Double) -> String {
  // Adding zero turns a rounded negative zero (-0.0) into plain zero.
  let value = value + 0.0
  let tenths = (value.abs() * 10.0).round()
  let whole = (tenths / 10.0).floor().to_int()
  let digit = (tenths % 10.0).to_int()
  let sign = if value < 0.0 { "-" } else { "" }

  //
  "\{sign}\{whole}.\{digit}"
}

///|
/// audit_fmt formats a millimetre value with one decimal in a fixed width.
fn audit_fmt(value : Double) -> String {
  audit_pad(audit_num(value), 7)
}

///|
/// audit_span formats a `[min, max]` range in millimetres.
fn audit_span(lo : Double, hi : Double) -> String {
  "[" + audit_fmt(lo) + "," + audit_fmt(hi) + "]"
}

///|
/// audit_max is the larger of two numbers.
fn audit_max(a : Double, b : Double) -> Double {
  if a > b {
    a
  } else {
    b
  }
}

///|
/// audit_gap is the distance between two axis-aligned boxes; zero when they
/// overlap or touch.
fn audit_gap(a : BodyAudit, b : BodyAudit) -> Double {
  let (ax0, ay0, az0) = a.min
  let (ax1, ay1, az1) = a.max
  let (bx0, by0, bz0) = b.min
  let (bx1, by1, bz1) = b.max

  //
  let gx = audit_max(audit_max(ax0 - bx1, bx0 - ax1), 0.0)
  let gy = audit_max(audit_max(ay0 - by1, by0 - ay1), 0.0)

  //
  let gz = audit_max(audit_max(az0 - bz1, bz0 - az1), 0.0)
  (gx * gx + gy * gy + gz * gz).sqrt()
}

///|
/// audit_pad pads `text` with leading spaces to `width` characters.
fn audit_pad(text : String, width : Int32) -> String {
  let mut out = text
  while out.length() < width {
    out = " " + out
  }

  //
  out
}

///|
/// audit_label right-aligns `label` and leaves at least one space after it.
fn audit_label(label : String, width : Int32) -> String {
  let room = label.length() + 1

  //
  audit_pad(label, if width > room { width } else { room })
}

///|
/// Component::audit_report prints every body's world bounding box and mass
/// (optionally only bodies whose link, body, or part name contains `filter`)
/// and checks that no body keeps a placeholder inertial. It then lists bodies
/// that touch no other body, which usually means a part is modeled floating
/// in mid-air. Bounding boxes are coarse, so the support list is advisory.
pub fn Component::audit_report(
  self : Component,
  filter~ : String = "",
  joint_positions~ : Map[String, Double] = Map([]),
) -> CheckReport {
  let all = self.audit_bodies(joint_positions~)
  let shown = all.filter(fn(a) {
    filter == "" ||
    a.link.contains(filter) ||
    a.body.contains(filter) ||
    a.part_number.contains(filter)
  })

  //
  // 1. Table of world bounding boxes and masses.
  let mut text = "link                     body                                    x range          y range          z range        mass g\n"
  for a in shown {
    text = text +
      audit_label(a.link, 24) +
      audit_label(a.body, 40) +
      audit_span(a.min.0, a.max.0) +
      "  " +
      audit_span(a.min.1, a.max.1) +
      "  " +
      audit_span(a.min.2, a.max.2) +
      "  " +
      audit_fmt(a.mass_kg * 1000.0) +
      "\n"
  }

  //
  // 2. Inertials that no longer describe the placed shape.
  let mut errors = 0
  let mut warnings = 0

  //
  for a in all {
    if a.solid_mass_kg > 0.0 {
      let ratio = a.mass_kg / a.solid_mass_kg
      if ratio < AuditMinInertiaRatio {
        errors = errors + 1
        text = text +
          "ERROR stale placeholder inertia: \{a.link}/\{a.body} weighs \{audit_fmt(a.mass_kg * 1000.0)} g but its shape holds \{audit_fmt(a.solid_mass_kg * 1000.0)} g; rebuild it with BodyPart::from_scene_node\n"
      } else if ratio > AuditMaxInertiaRatio {
        // Mesh volume is measured on an inscribed tessellation, so it reads
        // low for small or finely threaded parts; only advise here.
        warnings = warnings + 1
        text = text +
          "ADVISORY inertial is heavier than the measured shape: \{a.link}/\{a.body} weighs \{audit_fmt(a.mass_kg * 1000.0)} g but its shape measures \{audit_fmt(a.solid_mass_kg * 1000.0)} g\n"
      }
    }
  }

  //
  // 3. Bodies that touch nothing else (advisory).
  for a in all {
    let supported = all.any(fn(b) {
      !(b.link == a.link && b.body == a.body) &&
      audit_gap(a, b) <= AuditContactGapMm
    })
    if !supported {
      warnings = warnings + 1
      text = text +
        "ADVISORY touches nothing (floating?): \{a.link}/\{a.body} at \{audit_span(a.min.0, a.max.0)} \{audit_span(a.min.1, a.max.1)} \{audit_span(a.min.2, a.max.2)}\n"
    }
  }

  //
  { text, errors, warnings, }
}

///|
/// Component::audit_neighbors lists every body whose bounding box lies within
/// `radius_mm` of a body whose link, body, or part name contains `filter`.
/// Use it to see what a spring, screw, or magnet actually sits against.
pub fn Component::audit_neighbors(
  self : Component,
  filter : String,
  radius_mm~ : Double = 2.0,
  joint_positions~ : Map[String, Double] = Map([]),
) -> CheckReport {
  let all = self.audit_bodies(joint_positions~)
  let targets = all.filter(fn(a) {
    a.link.contains(filter) ||
    a.body.contains(filter) ||
    a.part_number.contains(filter)
  })
  let mut text = ""
  let mut errors = 0

  //
  if targets.is_empty() {
    errors = 1
    text = "ERROR no body matches '\{filter}'\n"
  }

  //
  for a in targets {
    text = text +
      "\{a.link}/\{a.body} \{audit_span(a.min.0, a.max.0)} \{audit_span(a.min.1, a.max.1)} \{audit_span(a.min.2, a.max.2)}\n"

    //
    for b in all {
      let same = b.link == a.link && b.body == a.body
      let gap = audit_gap(a, b)
      if !same && gap <= radius_mm {
        let label = if b.part_number == "" {
          b.link + "/" + b.body
        } else {
          b.link + "/" + b.body + " (" + b.part_number + ")"
        }
        text = text +
          "    gap \{audit_fmt(gap)} mm  \{label} \{audit_span(b.min.0, b.max.0)} \{audit_span(b.min.1, b.max.1)} \{audit_span(b.min.2, b.max.2)}\n"
      }
    }
  }

  //
  { text, errors, warnings: 0, }
}