///|
priv struct StringLengthRange {
  minimum : Int64
  maximum : Int64?
}

///|
fn StringLengthRange::allows(self : StringLengthRange, length : Int64) -> Bool {
  self.minimum <= length && length <= self.maximum.unwrap_or(length)
}

///|
fn StringLengthRange::allows_text(
  self : StringLengthRange,
  text : String,
) -> Bool {
  if self.minimum == 0L && self.maximum is None {
    return true
  }
  self.allows(text.iter().count().to_int64())
}

///|
fn compile_string(fields : Map[String, Json]) -> Domain raise SchemaIssue {
  let mut minimum = 0L
  let mut maximum = None
  for key, value in fields {
    match key {
      "type" | "enum" | "const" => ()
      "minLength" => minimum = nonnegative_length(value, key)
      "maxLength" => maximum = Some(nonnegative_length(value, key))
      _ => check_annotation(key, value)
    }
  }
  let range : StringLengthRange = { minimum, maximum, }
  match literal_candidates(fields) {
    None if range.allows(minimum) => Strings(StringLengths(range))
    None => Strings(StringValues([]))
    Some(values) => {
      let strings = []
      for candidate in values {
        if candidate is String(text) && range.allows_text(text) {
          strings.push(text)
        }
      }
      Strings(StringValues(strings))
    }
  }
}

///|
fn example_string(domain : StringDomain) -> Witness? {
  match domain {
    StringLengths(range) => Some(StringWitness(range.minimum, 'a'))
    StringValues(values) => first_rejected_string(values, _ => true)
  }
}

///|
fn first_rejected_string(
  values : Array[String],
  rejected : (String) -> Bool,
) -> Witness? {
  let mut oversized = None
  for text in values {
    if rejected(text) {
      let candidate = Literal(Json::string(text))
      if witness_size_floor(candidate) <= output_size_limit.to_int64() {
        return Some(candidate)
      }
      oversized = Some(candidate)
    }
  }
  oversized
}

///|
fn string_witness_units(length : Int64, first : Char) -> Int64 {
  length + (if length > 0L && first.to_int() > 0xffff { 1L } else { 0L })
}

///|
fn render_string(
  length : Int64,
  first : Char,
  budget : Ref[Int32],
) -> Json raise SchemaIssue {
  let units = string_witness_units(length, first)
  if units > budget.val.to_int64() {
    raise Unsupported("counterexample exceeds the output size limit")
  }
  spend_output_budget(budget, units.to_int())
  if length == 0L {
    Json::string("")
  } else {
    Json::string(first.to_string() + String::make(length.to_int() - 1, 'a'))
  }
}

///|
fn unlisted_string(accepted : Map[String, Unit]) -> Witness {
  let mut value = ""
  let mut index = 1
  while accepted.contains(value) {
    value = "value-\{index}"
    index += 1
  }
  Literal(Json::string(value))
}

///|
fn unlisted_string_of_length(
  length : Int64,
  accepted : Array[String],
) -> Witness raise SchemaIssue {
  // Vary one Unicode scalar and use 'a' for the remaining positions. A
  // finite enum excludes only the first characters of strings of that form.
  let used : Map[Char, Unit] = Map([])
  for text in accepted {
    let size = text.length().to_int64()
    if size < length || size > length + 1L {
      continue
    }
    let chars = text.iter()
    if chars.next() is Some(first) &&
      string_witness_units(length, first) == size &&
      chars.all(character => character == 'a') {
      used[first] = ()
    }
  }
  for code in 'a'.to_int()..<='z'.to_int() {
    let char = code.unsafe_to_char()
    if !used.contains(char) {
      return StringWitness(length, char)
    }
  }
  // Prefer a one-unit scalar so an astral character never uses extra space
  // while a smaller witness is still available. Exclude surrogates.
  for
    (start, end) in [
      (0x100, 0xd7ff),
      (0xe000, 0xffff),
      (0x30, 0xff),
      (0, 0x2f),
      (0x10000, 0x10ffff),
    ] {
    for code in start..<=end {
      let char = code.unsafe_to_char()
      if !used.contains(char) {
        return StringWitness(length, char)
      }
    }
  }
  raise Unsupported(
    "could not construct a string witness within the supported alphabet",
  )
}

///|
fn missing_string(
  source : StringDomain,
  target : StringDomain?,
) -> Witness? raise SchemaIssue {
  match (source, target) {
    (_, None) => example_string(source)
    (StringValues(source), Some(StringLengths(target))) =>
      first_rejected_string(source, value => !target.allows_text(value))
    (StringLengths(source), Some(StringLengths(target))) =>
      if !target.allows(source.minimum) {
        Some(StringWitness(source.minimum, 'a'))
      } else if target.maximum is Some(maximum) && source.allows(maximum + 1L) {
        Some(StringWitness(maximum + 1L, 'a'))
      } else {
        None
      }
    (StringLengths(source), Some(StringValues(target))) if source.minimum != 0L ||
      source.maximum is Some(_) => {
      let mut length = source.minimum
      if length == 0L {
        if !target.contains("") {
          return Some(StringWitness(0L, 'a'))
        }
        length = 1L
      }
      if source.allows(length) {
        Some(unlisted_string_of_length(length, target))
      } else {
        None
      }
    }
    (_, Some(StringValues(target))) => {
      let accepted : Map[String, Unit] = Map([])
      for value in target {
        accepted[value] = ()
      }
      match source {
        StringLengths(_) => Some(unlisted_string(accepted))
        StringValues(values) =>
          first_rejected_string(values, value => !accepted.contains(value))
      }
    }
  }
}