///|
/// A named attachment frame on a component.
///
/// The canonical definition lives in `gmlewis/step/components/common`; this
/// alias keeps the URDF-facing name without defining a second struct. The
/// shared connector stores millimetres and degrees internally and provides
/// `from_m_rad` / `to_m_rad` for the URDF XML boundary.
pub type MateConnector = @step_common.MateConnector

///|
/// origin_of_mate converts a shared connector frame to the URDF metre/radian
/// `Origin`.
fn origin_of_mate(mate : @step_common.MateConnector) -> Origin {
  let (xyz, rpy) = mate.to_m_rad()
  Origin::new(xyz~, rpy~)
}

///|
/// Applies the shared mate convention to a snapped joint axis.
///
/// For interfaces whose assembled axes are anti-parallel by convention
/// (shaft-into-bore and plane-on-plane), `MatePair::resolve` negates the axis
/// when it points along the child connector's own axis. Mirroring that rule
/// here keeps a URDF joint axis pointing the same way as the CAD-side mate.
fn align_mate_axis(
  parent_mate : MateConnector,
  child_mate : MateConnector,
  raw : Vec3,
) -> Vec3 {
  if @step_common.interface_anti_parallel(parent_mate.kind, child_mate.kind) {
    let child_axis = @step_common.normalize_dir(child_mate.axis)
    if @step_common.dir_dot(raw, child_axis) > 0.0 {
      return (-raw.0, -raw.1, -raw.2)
    }
  }

  //
  raw
}

///|
/// Snaps a child mate onto a parent mate. Returns the joint origin (the
/// child-link pose at `q = 0`) and the joint axis expressed in the child
/// frame.
///
/// This is a metre/radian wrapper around the shared `snap_connectors`; the
/// offset is converted to millimetres and the result back to a URDF `Origin`.
/// The returned axis follows the same anti-parallel insertion convention as
/// `@step_common.MatePair::resolve`, so a joint built from component
/// connectors uses the same axis direction as the CAD mate.
pub fn snap_mates(
  parent_mate : MateConnector,
  child_mate : MateConnector,
  offset~ : Double = 0.0,
  angle_rad~ : Double = 0.0,
  flip_axis~ : Bool = false,
) -> (Origin, Vec3) {
  let (placement, raw_axis) = @step_common.snap_connectors(
    parent_mate,
    child_mate,
    offset_mm=offset * 1000.0,
    twist_rad=angle_rad,
    flip_axis~,
  )
  let axis = align_mate_axis(parent_mate, child_mate, raw_axis)
  let (xyz, rpy) = @step_common.MateConnector::new("snap", placement~).to_m_rad()

  //
  (Origin::new(xyz~, rpy~), axis)
}

///|
/// Builds a joint by snapping a child component's mate onto a parent's mate.
pub fn Joint::from_mates(
  name : String,
  joint_type : JointType,
  parent_link~ : String,
  parent_mate~ : MateConnector,
  child_link~ : String,
  child_mate~ : MateConnector,
  offset~ : Double = 0.0,
  angle_rad~ : Double = 0.0,
  flip_axis~ : Bool = false,
  limit~ : JointLimit? = None,
  dynamics~ : JointDynamics? = None,
) -> Joint {
  let pair = @step_common.MatePair::new(
    parent=parent_mate.name,
    child=child_mate.name,
    offset_mm=offset * 1000.0,
    twist_deg=angle_rad * 180.0 / @math.PI,
    flip_axis~,
  )
  Joint::from_pair(
    name,
    joint_type,
    parent_link~,
    parent_mate~,
    child_link~,
    child_mate~,
    pair~,
    limit~,
    dynamics~,

    //
  )
}

///|
/// Builds a joint from a shared mate pair.
///
/// The pair owns the parent/child connector names, offset, twist, and flip;
/// kinematic data stays in the joint arguments. Callers that already use
/// `@step_common.MatePair` can pass it directly instead of restating its
/// geometric fields.
pub fn Joint::from_pair(
  name : String,
  joint_type : JointType,
  parent_link~ : String,
  parent_mate~ : MateConnector,
  child_link~ : String,
  child_mate~ : MateConnector,
  pair~ : @step_common.MatePair,
  limit~ : JointLimit? = None,
  dynamics~ : JointDynamics? = None,
) -> Joint {
  let (origin, axis) = snap_mates(
    parent_mate,
    child_mate,
    offset=pair.offset_mm / 1000.0,
    angle_rad=pair.twist_deg * @math.PI / 180.0,
    flip_axis=pair.flip_axis,
  )
  let joint = Joint::new(
    name,
    joint_type,
    parent=parent_link,
    child=child_link,
    origin~,
    axis~,
  )
  let joint = match limit {
    Some(lim) => joint.with_limit(lim)
    None => joint
  }

  //
  match dynamics {
    Some(d) => joint.with_dynamics(d)
    None => joint
  }
}

///|
fn rebase_origin(inv : Transform, origin : Origin) -> Origin {
  inv.compose(Transform::from_origin(origin)).to_origin()
}

///|
/// Moves the link's coordinate frame onto `mate`, rewriting every inertial,
/// visual, and collision origin accordingly. This is what makes a component
/// modeled around its own center usable as a URDF child link, whose pivot is
/// always at the link origin.
pub fn Link::rebase_to_mate(self : Link, mate : MateConnector) -> Link {
  let inv = Transform::from_origin(origin_of_mate(mate)).inverse()
  let visuals : Array[Visual] = []
  for visual in self.visuals {
    visuals.push({ ..visual, origin: rebase_origin(inv, visual.origin), })
  }
  let collisions : Array[Collision] = []
  for collision in self.collisions {
    collisions.push({
      ..collision,
      origin: rebase_origin(inv, collision.origin),
    })
  }
  let inertial = match self.inertial {
    Some(inertial) =>
      Some({ ..inertial, origin: rebase_origin(inv, inertial.origin), })
    None => None
  }

  //
  { ..self, inertial, visuals, collisions, }
}

///|
// Motion transform for one joint at its resolved position.
fn child_pose(
  t_parent : Transform,
  joint : Joint,
  q_map : Map[String, Double],
) -> Transform {
  let t_origin = Transform::from_origin(joint.origin)
  let q = q_map.get(joint.name).unwrap_or(0.0)
  let u = v3_norm(joint.axis)
  let motion = match joint.joint_type {
    Revolute | Continuous =>
      { rot: rotation_matrix_axis_angle(u, q), trans: (0.0, 0.0, 0.0), }
    Prismatic => { rot: Matrix3x3::identity(), trans: v3_scale(u, q), }
    _ => Transform::identity()
  }
  t_parent.compose(t_origin).compose(motion)
}

///|
// Scan fallback with an optional pass cap. Returns the pose map plus whether
// it settled within `max_passes`; a false flag means the caller should fall
// back to the indexed path (pathological joint ordering or very deep mimic
// chains).
fn scan_impl(
  robot : Robot,
  joint_positions : Map[String, Double],
  max_passes : Int32,
) -> (Map[String, Transform], Bool) {
  let poses : Map[String, Transform] = Map([])
  let child_names : Map[String, Unit] = Map([])
  for joint in robot.joints {
    child_names.set(joint.child, ())
  }
  for link in robot.links {
    if !child_names.contains(link.name) {
      poses.set(link.name, Transform::identity())
    }
  }

  // Seed non-mimic joint positions.
  let q_map : Map[String, Double] = Map([])
  for joint in robot.joints {
    if joint.mimic is None {
      q_map.set(joint.name, joint_positions.get(joint.name).unwrap_or(0.0))
    }
  }

  //
  // Resolve mimic chains (possibly chained) in repeated passes, stopping as
  // soon as a pass changes nothing (typically 1-2 passes even for mimic
  // chains, versus the old always-`n` passes).
  let mut mimic_settled = false
  for _ in 0.. child until no more links can be resolved, so the
  // order of joints in the robot does not matter. Stops after a pass that
  // places no new link, instead of always running `n` passes.
  let mut propagated = false
  for _ in 0.. Map[String, Transform] {
  scan_impl(robot, joint_positions, robot.joints.length()).0
}

///|
/// Computes world poses for every link reachable from the robot's root
/// link(s). Mimic joints are resolved before propagation.
pub fn Robot::forward_kinematics(
  self : Robot,
  joint_positions~ : Map[String, Double] = Map([]),
) -> Map[String, Transform] {
  let n = self.joints.length()

  // For short chains, scan is fastest and always finishes within `n` passes.
  if n <= 16 {
    return forward_kinematics_scan(self, joint_positions)
  }

  // Dependency-ordered input (the common case) settles within a few passes,
  // so give the scan a small pass budget. If it cannot settle — scrambled or
  // reversed joint order, or very deep mimic chains — fall back to the
  // indexed algorithm below.
  let (poses, settled) = scan_impl(self, joint_positions, 32)
  if settled {
    return poses
  }

  // Build the index once; it also detects duplicate joint names and
  // competing parent joints, in which case the scan's semantics are
  // preserved by deferring to it.
  let children : Map[String, Array[Int32]] = Map([])
  let mimic_users : Map[String, Array[Int32]] = Map([])
  let q_map : Map[String, Double] = Map([])
  let q_queue : Array[String] = []
  let seen : Map[String, Unit] = Map([])
  let child_names : Map[String, Unit] = Map([])
  for i in 0.. indices.push(i)
      None => children.set(joint.parent, [i])
    }
    match joint.mimic {
      Some(mimic) =>
        match mimic_users.get(mimic.joint) {
          Some(indices) => indices.push(i)
          None => mimic_users.set(mimic.joint, [i])
        }
      None => {
        q_map.set(joint.name, joint_positions.get(joint.name).unwrap_or(0.0))
        q_queue.push(joint.name)
      }
    }
  }

  // Every reachable mimic has a unique driver and gets exactly one
  // evaluation. Missing drivers and cycles leave q unset. A reachable link
  // still gets its pose with zero joint motion, as in the scan.
  let mut q_head = 0
  while q_head < q_queue.length() {
    let name = q_queue[q_head]
    q_head = q_head + 1
    match mimic_users.get(name) {
      Some(indices) =>
        for i in indices {
          let joint = self.joints[i]
          if joint.mimic is Some(mimic) {
            let q_ref = q_map.get(name).unwrap_or(0.0)
            q_map.set(joint.name, mimic.multiplier * q_ref + mimic.offset)
            q_queue.push(joint.name)
          }
        }
      None => ()
    }
  }

  //
  let poses : Map[String, Transform] = Map([])

  // (link name, old scan pass, index of the joint that first produced it).
  let frontier : Array[(String, Int32, Int32)] = []
  for link in self.links {
    if !child_names.contains(link.name) {
      if !poses.contains(link.name) {
        frontier.push((link.name, 0, -1))
      }
      poses.set(link.name, Transform::identity())
    }
  }

  // A root is ready before joint 0. After joint k places a parent, the scan
  // can still visit indices greater than k on this pass. Earlier ones wait
  // for the next pass.
  let passes : Array[Int32] = Array::make(n, -1)
  let mut head = 0
  while head < frontier.length() {
    let (name, parent_pass, parent_joint_index) = frontier[head]
    head = head + 1
    match children.get(name) {
      Some(indices) =>
        for i in indices {
          if passes[i] < 0 {
            let child_pass = if i > parent_joint_index {
              parent_pass
            } else {
              parent_pass + 1
            }
            passes[i] = child_pass
            frontier.push((self.joints[i].child, child_pass, i))
          }
        }
      None => ()
    }
  }

  // Stable buckets preserve the map insertion order of the old scans as
  // well as the numerical operation order along each kinematic path.
  let buckets : Array[Array[Int32]] = []
  for i in 0..= 0 {
      while buckets.length() <= passes[i] {
        buckets.push([])
      }
      buckets[passes[i]].push(i)
    }
  }
  for bucket in buckets {
    for i in bucket {
      let joint = self.joints[i]
      let t_parent = poses.get(joint.parent).unwrap()
      poses.set(joint.child, child_pose(t_parent, joint, q_map))
    }
  }

  //
  poses
}

///|
/// Convenience wrapper returning each link's world origin (xyz + rpy).
pub fn Robot::link_world_origins(
  self : Robot,
  joint_positions~ : Map[String, Double] = Map([]),
) -> Map[String, Origin] {
  let poses = self.forward_kinematics(joint_positions~)
  let out : Map[String, Origin] = Map([])
  for name, transform in poses {
    out.set(name, transform.to_origin())
  }

  //
  out
}