///|
pub impl ToJson for Point with fn to_json(self) {
  { "x": ToJson::to_json(self.x), "y": ToJson::to_json(self.y) }
}

///|
pub extend Point with ToJson::{to_json}

///|
pub impl ToJson for LanePosition with fn to_json(self) {
  {
    "road_id": ToJson::to_json(self.road_id),
    "lane_id": ToJson::to_json(self.lane_id),
    "section_index": ToJson::to_json(self.section_index),
    "section_start": ToJson::to_json(self.section_start),
    "s": ToJson::to_json(self.s),
    "center": ToJson::to_json(self.center),
    "inner": ToJson::to_json(self.inner),
    "outer": ToJson::to_json(self.outer),
    "width": ToJson::to_json(self.width),
  }
}

///|
pub extend LanePosition with ToJson::{to_json}

///|
fn LaneSpan::json(self : LaneSpan) -> Json {
  {
    "road_id": ToJson::to_json(self.road_id),
    "lane_id": ToJson::to_json(self.lane_id),
    "section_index": ToJson::to_json(self.section_index),
    "section_start": ToJson::to_json(self.section_start),
    "points": ToJson::to_json(self.points),
  }
}

///|
/// Serialize sampled geometries to the version 1 map-local JSON format.
pub fn export_json(
  map : RoadMap,
  max_step~ : Double = 1.0,
  limits~ : Limits = Limits::new(),
) -> Json raise RoadError {
  {
    "schema_version": 1,
    "mode": "planar",
    "coordinate_system": "map-local-xy-metres",
    "opendrive_minor": ToJson::to_json(map.minor),
    "spans": Json::array(
      sample_map(map, max_step, limits).map(fn(span) { span.json() }),
    ),
  }
}

///|
priv struct Bounds {
  mut xmin : Double
  mut ymin : Double
  mut xmax : Double
  mut ymax : Double
}

///|
fn Bounds::visit(self : Bounds, p : Point) -> Unit {
  self.xmin = self.xmin.min(p.x)
  self.ymin = self.ymin.min(-p.y)
  self.xmax = self.xmax.max(p.x)
  self.ymax = self.ymax.max(-p.y)
}

///|
fn svg_line(
  builder : StringBuilder,
  points : Array[LanePosition],
  name : String,
  color : String,
  pick : (LanePosition) -> Point,
) -> Unit {
  builder.write_string(
    "     0 {
      builder.write_char(' ')
    }
    let p = pick(position)
    builder.write_string("\{p.x},\{-p.y}")
  }
  builder.write_string("\"/>\n")
}

///|
/// Export planar lane boundaries and centers to SVG. SVG reverses the
/// map y coordinate to preserve the map's visual orientation on screen.
pub fn export_svg(
  map : RoadMap,
  max_step~ : Double = 1.0,
  limits~ : Limits = Limits::new(),
) -> String raise RoadError {
  let spans = sample_map(map, max_step, limits)
  let bounds = {
    xmin: 1.0 / 0.0,
    ymin: 1.0 / 0.0,
    xmax: -1.0 / 0.0,
    ymax: -1.0 / 0.0,
  }
  for span in spans {
    for p in span.points {
      bounds.visit(p.inner)
      bounds.visit(p.outer)
      bounds.visit(p.center)
    }
  }
  let view = if spans.is_empty() {
    "0 0 1 1"
  } else {
    let width = (bounds.xmax - bounds.xmin).max(1.0)
    let height = (bounds.ymax - bounds.ymin).max(1.0)
    if !finite(width) || !finite(height) {
      raise diagnostic(InvalidValue, "SVG bounds exceed floating-point range")
    }
    let margin = (width.max(height) * 0.02).min(1.0)
    "\{bounds.xmin - margin} \{bounds.ymin - margin} \{width + margin * 2.0} \{height + margin * 2.0}"
  }
  let builder = StringBuilder()
  builder.write_string(
    "\n",
  )
  for span in spans {
    let id = @xml.escape(span.road_id)
    builder.write_string(
      "  \n",
    )
    svg_line(builder, span.points, "inner", "#263746", fn(p) { p.inner })
    svg_line(builder, span.points, "outer", "#263746", fn(p) { p.outer })
    svg_line(builder, span.points, "center", "#2875a8", fn(p) { p.center })
    builder.write_string("  \n")
  }
  builder.write_string("\n")
  builder.to_string()
}