///|
/// One continuous interval of a sampled lane. Adjacent spans can each carry
/// a position at their shared station to retain both sides of a breakpoint.
pub struct LaneSpan {
  road_id : String
  lane_id : Int32
  section_index : Int32
  section_start : Double
  points : Array[LanePosition]
}

///|
priv struct SampleBudget {
  mut remaining : Int32
  max_step : Double
}

///|
fn SampleBudget::new(
  limits : Limits,
  max_step : Double,
) -> SampleBudget raise RoadError {
  if !finite(max_step) || max_step <= 0.0 || limits.max_samples <= 0 {
    raise diagnostic(
      InvalidValue,
      "maximum step and sample limit must be positive and finite",
    )
  }
  { remaining: limits.max_samples, max_step, }
}

///|
fn sample_limit(road_id : String, lane_id : Int32, s : Double) -> RoadError {
  diagnostic(
    LimitExceeded,
    "sample point limit exceeded",
    road_id~,
    lane_id~,
    s~,
  )
}

///|
fn[T] add_road_breaks(
  out : Array[Double],
  records : Array[T],
  lo : Double,
  hi : Double,
  start : (T) -> Double,
) -> Unit {
  let first = active_index(records, lo, start) + 1
  for i in first..= hi {
      break
    }
    out.push(s)
  }
}

///|
fn Road::section_end(self : Road, index : Int32) -> Double {
  if index + 1 == self.sections.length() {
    self.length
  } else {
    self.sections[index + 1].s
  }
}

///|
fn Road::sample_section(
  self : Road,
  section_index : Int32,
  lane_id : Int32,
  budget : SampleBudget,
  output : Array[LaneSpan],
) -> Unit raise RoadError {
  let section = self.sections[section_index]
  let lo = section.s
  let hi = self.section_end(section_index)
  if budget.remaining < 2 {
    raise sample_limit(self.id, lane_id, lo)
  }
  let breaks = [lo, hi]
  add_road_breaks(breaks, self.plan, lo, hi, fn(part) { part.s })
  add_road_breaks(breaks, self.offsets, lo, hi, fn(record) { record.start })
  let side = section.side(lane_id)
  for i in 0.. lo && s < hi {
        breaks.push(s)
      }
    }
  }
  breaks.sort()
  let mut start = lo
  for end in breaks {
    if end == start {
      continue
    }
    self.sample_interval(section_index, lane_id, start, end, budget, output)
    start = end
  }
}

///|
fn Road::sample_interval(
  self : Road,
  section_index : Int32,
  lane_id : Int32,
  start : Double,
  end : Double,
  budget : SampleBudget,
  output : Array[LaneSpan],
) -> Unit raise RoadError {
  let span = end - start
  let subdivisions = @math.ceil(span / budget.max_step).max(1.0)
  if !finite(subdivisions) || subdivisions >= budget.remaining.to_double() {
    raise sample_limit(self.id, lane_id, start)
  }
  let count = subdivisions.to_int()
  budget.remaining -= count + 1
  let points = Array(capacity=count + 1)
  let mut previous = start
  for i in 0..<=count {
    let s = if i == count {
      end
    } else {
      start + span * (i.to_double() / subdivisions)
    }
    if (i > 0 && s <= previous) || (i < count && s >= end) {
      raise diagnostic(
        InvalidValue,
        "sample step is below station precision",
        road_id=self.id,
        lane_id~,
        s~,
      )
    }
    points.push(self.lane_at(lane_id, section_index, s, start))
    previous = s
  }
  output.push({
    road_id: self.id,
    lane_id,
    section_index,
    section_start: self.sections[section_index].s,
    points,
  })
}

///|
/// Sample every section of this road where the specified lane exists.
pub fn sample_lane(
  map : RoadMap,
  road_id : String,
  lane_id : Int32,
  max_step~ : Double = 1.0,
  limits~ : Limits = Limits::new(),
) -> Array[LaneSpan] raise RoadError {
  let budget = SampleBudget::new(limits, max_step)
  let road = map.find_road(road_id, lane_id~)
  let output = []
  for i, section in road.sections {
    let count = section.side(lane_id).length()
    if lane_id != 0 && lane_id >= -count && lane_id <= count {
      road.sample_section(i, lane_id, budget, output)
    }
  }
  if output.is_empty() {
    raise diagnostic(
      LaneNotFound,
      "lane does not exist on this road",
      road_id~,
      lane_id~,
    )
  }
  output
}

///|
fn sample_map(
  map : RoadMap,
  max_step : Double,
  limits : Limits,
) -> Array[LaneSpan] raise RoadError {
  let budget = SampleBudget::new(limits, max_step)
  let output = []
  for road in map.roads {
    for i, section in road.sections {
      for lane in section.left {
        road.sample_section(i, lane.id, budget, output)
      }
      for lane in section.right {
        road.sample_section(i, lane.id, budget, output)
      }
    }
  }
  output
}