///|
pub(all) struct Finding {
  field : String
  reason : String
  witness : Json
}

///|
fn number(n : Int32) -> Json {
  Json::number(n.to_double())
}

///|
fn sample(domain : Domain) -> Json {
  match domain {
    Integer(low, _) => number(low)
    Text(Some(values)) => Json::string(values.sorted[0])
    Text(None) => Json::string("")
    Flag => Json::boolean(false)
  }
}

///|
fn outside_enum(values : EnumValues) -> Json {
  let mut s = ""
  while values.members.contains(s) {
    s = s + "x"
  }
  Json::string(s)
}

///|
fn difference(source_field : Field, target_field : Field) -> Json? {
  if source_field.nullable && !target_field.nullable {
    return Some(Json::null())
  }
  match (source_field.domain, target_field.domain) {
    (Integer(low, high), Integer(target_low, target_high)) =>
      if low < target_low || low > target_high {
        Some(number(low))
      } else if high > target_high {
        Some(number(high))
      } else {
        None
      }
    (Flag, Flag) | (Text(_), Text(None)) => None
    (Text(None), Text(Some(allowed))) => Some(outside_enum(allowed))
    (Text(Some(old)), Text(Some(new))) => {
      let values = old.sorted
      let allowed = new.sorted
      // Use the target's existing index when scanning its choices costs more.
      if values.length() * 4 <= allowed.length() {
        for value in values {
          if !new.members.contains(value) {
            return Some(Json::string(value))
          }
        }
        return None
      }
      // The parser sorts both lists. Advance the target cursor only once per value.
      let mut j = 0
      for value in values {
        while j < allowed.length() && allowed[j] != value {
          if allowed[j] > value {
            return Some(Json::string(value))
          }
          j += 1
        }
        if j == allowed.length() {
          return Some(Json::string(value))
        }
        j += 1
      }
      None
    }
    // The supported non-null types have disjoint value domains.
    (source, _) => Some(sample(source))
  }
}

///|
fn required_record(source : Contract) -> Map[String, Json] {
  let record : Map[String, Json] = Map([])
  // The parsed contract already keeps these in field order.
  for (name, field) in source.required_fields {
    record[name] = sample(field.domain)
  }
  record
}

///|
fn witness(base : Map[String, Json], extra : (String, Json)?) -> Json {
  let record = base.copy()
  if extra is Some((name, value)) {
    record[name] = value
  }
  Json::object(record)
}

///|
/// Check inclusion: every record admitted by source must be admitted by target.
/// Each finding carries a record admitted by source and rejected by target.
pub fn compare(source : Contract, target : Contract) -> Array[Finding] {
  let findings : Array[Finding] = []
  let mut baseline : Map[String, Json]? = None
  let make_witness = fn(extra : (String, Json)?) {
    let base = match baseline {
      Some(saved) => saved
      None => {
        let record = required_record(source)
        baseline = Some(record)
        record
      }
    }
    witness(base, extra)
  }
  let mut matched_source_fields = 0
  for (name, next) in target.ordered {
    let previous = source.fields.get(name)
    if next.required && !(previous is Some(field) && field.required) {
      findings.push({
        field: name,
        reason: "new_required",
        witness: make_witness(None),
      })
    }
    match previous {
      Some(field) => {
        matched_source_fields += 1
        if difference(field, next) is Some(value) {
          findings.push({
            field: name,
            reason: "narrowed_domain",
            witness: make_witness(Some((name, value))),
          })
        }
      }
      None if source.open => {
        let rejected = if next.nullable {
          Json::array([])
        } else {
          Json::null()
        }
        findings.push({
          field: name,
          reason: "previously_unrestricted",
          witness: make_witness(Some((name, rejected))),
        })
      }
      None => ()
    }
  }
  if !target.open {
    // The target walk already establishes whether every source field survived.
    if matched_source_fields < source.ordered.length() {
      for (name, field) in source.ordered {
        if !target.fields.contains(name) {
          findings.push({
            field: name,
            reason: "removed_field",
            witness: make_witness(Some((name, sample(field.domain)))),
          })
        }
      }
    }
    if source.open {
      let mut extra = "_extra"
      let mut i = 0
      while source.fields.contains(extra) || target.fields.contains(extra) {
        extra = "_extra" + i.to_string()
        i += 1
      }
      findings.push({
        field: extra,
        reason: "closed_record",
        witness: make_witness(Some((extra, Json::null()))),
      })
    }
  }
  findings
}