///|
/// Independent limits for XML input and generated lane positions.
pub struct Limits {
  max_bytes : Int32
  max_nodes : Int32
  max_depth : Int32
  max_string : Int32
  max_roads : Int32
  max_samples : Int32
}

///|
pub fn Limits::new(
  max_bytes~ : Int32 = 16777216,
  max_nodes~ : Int32 = 250000,
  max_depth~ : Int32 = 64,
  max_string~ : Int32 = 65536,
  max_roads~ : Int32 = 10000,
  max_samples~ : Int32 = 200000,
) -> Limits {
  { max_bytes, max_nodes, max_depth, max_string, max_roads, max_samples, }
}

///|
#derive(Eq, @debug.Debug)
pub(all) enum ErrorCode {
  XmlSyntax
  MissingField
  InvalidValue
  InvalidLayout
  UnsupportedVersion
  UnsupportedFeature
  LimitExceeded
  RoadNotFound
  LaneNotFound
  InvalidStation
}

///|
#derive(@debug.Debug)
pub struct Diagnostic {
  code : ErrorCode
  message : String
  line : Int32?
  column : Int32?
  road_id : String?
  lane_id : Int32?
  s : Double?
}

///|
#derive(@debug.Debug)
pub(all) suberror RoadError {
  Failure(Diagnostic)
}

///|
/// A validated planar map. Road ordering follows the input document.
#derive(@debug.Debug)
pub struct RoadMap {
  priv minor : Int32
  priv roads : Array[Road]
  priv by_id : Map[String, Int32]
}

///|
pub fn RoadMap::revision_minor(self : RoadMap) -> Int32 {
  self.minor
}

///|
pub fn RoadMap::road_ids(self : RoadMap) -> Array[String] {
  self.roads.map(fn(road) { road.id })
}

///|
pub fn RoadMap::road_length(self : RoadMap, id : String) -> Double? {
  self.by_id.get(id).map(fn(index) { self.roads[index].length })
}

///|
#derive(@debug.Debug)
priv struct Road {
  id : String
  length : Double
  plan : Array[PlanSegment]
  offsets : Array[Cubic]
  sections : Array[LaneSection]
}

///|
#derive(@debug.Debug)
priv struct PlanSegment {
  s : Double
  x : Double
  y : Double
  heading : Double
  length : Double
  curvature : Double
}

///|
#derive(@debug.Debug)
priv struct LaneSection {
  s : Double
  left : Array[Lane]
  right : Array[Lane]
}

///|
#derive(@debug.Debug)
priv struct Lane {
  id : Int32
  widths : Array[Cubic]
}

///|
#derive(@debug.Debug)
priv struct Cubic {
  start : Double
  a : Double
  b : Double
  c : Double
  d : Double
}

///|
fn Cubic::at(self : Cubic, u : Double) -> Double {
  self.a + self.b * u + self.c * u * u + self.d * u * u * u
}

///|
fn finite(value : Double) -> Bool {
  !value.is_nan() && !value.is_inf()
}

///|
fn diagnostic(
  code : ErrorCode,
  message : String,
  line? : Int32,
  column? : Int32,
  road_id? : String,
  lane_id? : Int32,
  s? : Double,
) -> RoadError {
  Failure({ code, message, line, column, road_id, lane_id, s, })
}

///|
pub extend ErrorCode with Eq::{not_equal, equal}

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

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

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

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