///|
/// A point in map-local Cartesian metres with the original y direction.
#derive(@debug.Debug)
pub struct Point {
  x : Double
  y : Double
}

///|
pub extend Point with @debug.Debug::{to_repr}

///|
/// Reference-line pose evaluated directly at a road station.
#derive(@debug.Debug)
pub struct ReferencePosition {
  road_id : String
  s : Double
  segment_start : Double
  point : Point
  heading : Double
}

///|
pub extend ReferencePosition with @debug.Debug::{to_repr}

///|
/// A single cross section of a nonzero lane. Inner is closest to lane zero.
#derive(@debug.Debug)
pub struct LanePosition {
  road_id : String
  lane_id : Int32
  section_index : Int32
  section_start : Double
  s : Double
  center : Point
  inner : Point
  outer : Point
  width : Double
}

///|
pub extend LanePosition with @debug.Debug::{to_repr}

///|
fn RoadMap::find_road(
  self : RoadMap,
  id : String,
  lane_id? : Int32,
  s? : Double,
) -> Road raise RoadError {
  match self.by_id.get(id) {
    Some(index) => self.roads[index]
    None =>
      raise diagnostic(
        RoadNotFound,
        "road ID does not exist",
        road_id=id,
        lane_id?,
        s?,
      )
  }
}

///|
fn Road::check_station(
  self : Road,
  s : Double,
  lane_id? : Int32,
) -> Unit raise RoadError {
  if !finite(s) || s < 0.0 || s > self.length {
    raise diagnostic(
      InvalidStation,
      "station must be finite and within the road",
      road_id=self.id,
      lane_id?,
      s~,
    )
  }
}

///|
/// Index of the last record whose start is at or before the selector.
fn[T] active_index(
  records : Array[T],
  selector : Double,
  start : (T) -> Double,
) -> Int32 {
  let mut lo = 0
  let mut hi = records.length()
  while lo < hi {
    let mid = lo + (hi - lo) / 2
    if start(records[mid]) <= selector {
      lo = mid + 1
    } else {
      hi = mid
    }
  }
  lo - 1
}

///|
fn Road::reference_at(
  self : Road,
  s : Double,
  selector : Double,
) -> ReferencePosition {
  let segment = self.plan[active_index(self.plan, selector, fn(part) { part.s })]
  let ds = (s - segment.s).max(0.0).min(segment.length)
  let angle = segment.curvature * ds
  let half = angle * 0.5
  // The chord form avoids subtracting almost equal sin/cos values.
  let scale = if half == 0.0 { 1.0 } else { @math.sin(half) / half }
  let travel = ds * scale
  let direction = segment.heading + half
  let point = {
    x: segment.x + travel * @math.cos(direction),
    y: segment.y + travel * @math.sin(direction),
  }
  {
    road_id: self.id,
    s,
    segment_start: segment.s,
    point,
    heading: segment.heading + angle,
  }
}

///|
/// Query the reference line. Each internal breakpoint selects the next
/// interval, and the final road station belongs to the last interval.
pub fn reference_position(
  map : RoadMap,
  road_id : String,
  s : Double,
) -> ReferencePosition raise RoadError {
  let road = map.find_road(road_id, s~)
  road.check_station(s)
  road.reference_at(s, s)
}

///|
fn LaneSection::side(self : LaneSection, lane_id : Int32) -> Array[Lane] {
  if lane_id > 0 {
    self.left
  } else {
    self.right
  }
}

///|
fn cubic_at(
  records : Array[Cubic],
  base : Double,
  s : Double,
  selector : Double,
) -> Double {
  let i = active_index(records, selector, fn(record) { base + record.start })
  if i < 0 {
    0.0
  } else {
    let record = records[i]
    record.at((s - base - record.start).max(0.0))
  }
}

///|
fn translated(point : Point, nx : Double, ny : Double, t : Double) -> Point {
  { x: point.x + nx * t, y: point.y + ny * t, }
}

///|
fn Road::lane_at(
  self : Road,
  lane_id : Int32,
  section_index : Int32,
  s : Double,
  selector : Double,
) -> LanePosition raise RoadError {
  let section = self.sections[section_index]
  let side = section.side(lane_id)
  if lane_id == 0 || lane_id > side.length() || lane_id < -side.length() {
    raise diagnostic(
      LaneNotFound,
      "lane does not exist at this station",
      road_id=self.id,
      lane_id~,
      s~,
    )
  }
  let step = if lane_id > 0 { 1.0 } else { -1.0 }
  let index = lane_id.abs() - 1
  let mut inner_t = cubic_at(self.offsets, 0.0, s, selector)
  for i in 0.. LanePosition raise RoadError {
  let road = map.find_road(road_id, lane_id~, s~)
  road.check_station(s, lane_id~)
  let section_index = active_index(road.sections, s, fn(section) { section.s })
  road.lane_at(lane_id, section_index, s, s)
}