///|
/// Constructs a reusable custom table from `(source byte, replacement)` pairs.
///
/// Sources must be unique and within 0..126, as accepted by `v_escape` 1.0.0
/// at the documented source revision. Pair order is irrelevant. Raises
/// `EmptyTable`, `InvalidSource(byte)`, or `DuplicateSource(byte)` on invalid
/// mappings. `InvalidReplacement(source, code_unit_offset)` rejects an unpaired
/// surrogate before UTF-8 encoding on every backend. Empty replacements delete
/// a source; well-formed Unicode replacements are allowed. Byte operations emit
/// their UTF-8 encoding and text preserves their code units. The input array
/// is copied, never mutated or retained.
///
/// ```mbt check
/// test {
///   let escaper = @escape.Escaper::new([(b'<', "<"), (b'\"', """)])
///   assert_eq(escaper.escape("Hello,< world!\""), "Hello,< world!"")
/// }
/// ```
pub fn Escaper::new(
  pairs : ArrayView[(Byte, String)],
) -> Escaper raise EscapeError {
  guard !pairs.is_empty() else { raise EmptyTable }
  let table : FixedArray[Replacement?] = FixedArray::make(128, None)
  for (source, text) in pairs {
    guard source < 127 else { raise InvalidSource(source) }
    let index = source.to_int()
    guard table[index] is None else { raise DuplicateSource(source) }
    if invalid_surrogate(text) is Some(offset) {
      raise InvalidReplacement(source~, code_unit_offset=offset)
    }
    table[index] = Some({ text, bytes: @utf8.encode(text), })
  }
  let sources : Array[Byte] = []
  for index in 0..<127 {
    if table[index] is Some(_) {
      sources.push(index.to_byte())
    }
  }
  { table, ranges: bounding_ranges(sources), kind: Custom, }
}

///|
/// Locates an unpaired replacement surrogate before the backend-dependent UTF-8 encoder.
fn invalid_surrogate(text : String) -> Int32? {
  for index = 0; index < text.length(); {
    let unit = text[index]
    if unit is (0xd800..<=0xdbff) {
      if index + 1 >= text.length() || !(text[index + 1] is (0xdc00..<=0xdfff)) {
        return Some(index)
      }
      continue index + 2
    } else if unit is (0xdc00..<=0xdfff) {
      return Some(index)
    } else {
      continue index + 1
    }
  } nobreak {
    None
  }
}

///|
/// Splits sorted sources at their two widest gaps, bounding them by at most three ranges.
fn bounding_ranges(sources : ArrayView[Byte]) -> ReadOnlyArray[(Byte, Byte)] {
  let mut first = -1
  let mut second = -1
  let mut first_gap = 1
  let mut second_gap = 1
  for index in 0..<(sources.length() - 1) {
    let gap = sources[index + 1].to_int() - sources[index].to_int()
    if gap > first_gap {
      second = first
      second_gap = first_gap
      first = index
      first_gap = gap
    } else if gap > second_gap {
      second = index
      second_gap = gap
    }
  }
  if first > second {
    let old = first
    first = second
    second = old
  }
  let ranges : Array[(Byte, Byte)] = []
  let mut start = 0
  for split in [first, second] {
    if split >= 0 {
      ranges.push((sources[start], sources[split]))
      start = split + 1
    }
  }
  ranges.push((sources[start], sources[sources.length() - 1]))
  ReadOnlyArray::from_array(ranges)
}

///|
/// Builds a trusted preset with immutable tables and its specialized mask selector.
fn preset(pairs : ArrayView[(Byte, String)], kind : MaskKind) -> Escaper {
  let escaper = try! Escaper::new(pairs)
  { table: escaper.table, ranges: escaper.ranges, kind, }
}