///|
/// One through-hole of an extruded profile, measured in the assembled
/// (world) frame.
pub(all) struct HoleInfo {
  /// Link name of the compiled robot that owns the body.
  link : String
  /// Body name within its link.
  body : String
  /// Zero-based position of the hole in the profile's hole list.
  index : Int32
  /// Center of the hole where it enters the profile, in millimetres.
  from : (Double, Double, Double)
  /// Center of the hole where it leaves the profile, in millimetres.
  to : (Double, Double, Double)
  /// Narrowest opening of the hole, in millimetres (the bore diameter for a
  /// round hole, the slot width for a slot).
  width_mm : Double
  /// Longest opening of the hole through its center, in millimetres (equal to
  /// `width_mm` for a round hole).
  length_mm : Double
  /// Thinnest wall between the hole and the profile's outer boundary, in
  /// millimetres.
  wall_mm : Double
}

///|
/// Component::profile_holes lists every hole of every `ExtrudedArcProfile`
/// body with its world-frame entry and exit centers at the given joint
/// positions. A hole that lands somewhere unexpected shows up here
/// immediately, without deriving rotation signs by hand.
pub fn Component::profile_holes(
  self : Component,
  joint_positions~ : Map[String, Double] = Map([]),
) -> Array[HoleInfo] {
  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[HoleInfo] = []

  //
  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)
      match placed.shape {
        @step_cad.Shape::ExtrudedArcProfile(e) => {
          let xform = @step_cad.Transform::from_node(placed)

          //
          for i, hole in e.hole_info() {
            let (cx, cy) = hole.center_mm
            out.push({
              link: link.name,
              body: body.node.name,
              index: i,
              from: xform.apply((cx, cy, 0.0)),
              to: xform.apply((cx, cy, e.height_mm)),
              width_mm: hole.inner_radius_mm * 2.0,
              length_mm: hole.outer_radius_mm * 2.0,
              wall_mm: hole.wall_mm,
            })
          }
        }
        _ => ()
      }
    }
  }

  //
  out
}

///|
/// Component::hole_report prints the world position of every profile hole
/// (optionally only holes whose link or body name contains `filter`) and
/// checks each extruded profile: its holes must lie inside the outer
/// boundary, and it reports holes that leave less than `min_wall_mm` of
/// material. An invalid profile is an error because the STEP writer emits no
/// geometry for it at all.
pub fn Component::hole_report(
  self : Component,
  filter~ : String = "",
  min_wall_mm~ : Double = 0.6,
  joint_positions~ : Map[String, Double] = Map([]),
) -> CheckReport {
  let mut text = "link                                       body                                   hole  entry (mm)                    exit (mm)                     width  wall\n"
  let mut errors = 0
  let mut warnings = 0

  //
  // 1. Table of hole positions in the assembled frame.
  for hole in self.profile_holes(joint_positions~) {
    let skip = filter != "" &&
      !(hole.link.contains(filter) || hole.body.contains(filter))
    if skip {
      continue
    }
    if hole.wall_mm < min_wall_mm {
      warnings = warnings + 1
    }
    text = text +
      audit_label(hole.link, 42) +
      audit_label(hole.body, 38) +
      audit_label(hole.index.to_string(), 5) +
      hole_point(hole.from) +
      "  " +
      hole_point(hole.to) +
      "  " +
      audit_fmt(hole.width_mm) +
      "  " +
      audit_fmt(hole.wall_mm) +
      (if hole.length_mm <= hole.width_mm + 0.05 {
        ""
      } else {
        "  (slot \{audit_fmt(hole.length_mm)} long)"
      }) +
      "\n"
  }

  //
  // 2. Profile validity: a bad profile emits no STEP geometry at all.
  let (links, _, _) = self.compile_links()

  //
  for link in links {
    for body in link.bodies {
      match body.node.shape {
        @step_cad.Shape::ExtrudedArcProfile(e) => {
          let name = "\{link.name}/\{body.node.name}"
          if filter != "" &&
            !(link.name.contains(filter) || body.node.name.contains(filter)) {
            continue
          }
          if !e.holes_contained() {
            errors = errors + 1
            text = text +
              "ERROR a hole crosses the outer boundary or another hole: \{name}; move the hole inward or shrink it\n"
          } else if !e.validate() {
            errors = errors + 1
            text = text +
              "ERROR invalid profile (the STEP writer skips it): \{name}; loops must be closed and counter-clockwise with positive height\n"
          } else if e.holes.length() > 0 && e.min_hole_wall_mm() < min_wall_mm {
            warnings = warnings + 1
            text = text +
              "ADVISORY thin wall \{audit_fmt(e.min_hole_wall_mm())} mm around a hole in \{name} (minimum \{audit_fmt(min_wall_mm)} mm)\n"
          }
        }
        _ => ()
      }
    }
  }

  //
  { text, errors, warnings, }
}

///|
/// hole_point formats a world point as `(x, y, z)`.
fn hole_point(p : (Double, Double, Double)) -> String {
  "(\{audit_num(p.0)}, \{audit_num(p.1)}, \{audit_num(p.2)})"
}