///|
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[0])
    Text(None) => Json::string("")
    Flag => Json::boolean(false)
  }
}

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

///|
fn difference(source : Domain, target : Domain) -> Json? {
  if source is Text(Some(values)) && target is Text(Some(allowed)) {
    // 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
    }
    return None
  }
  let first = sample(source)
  if !accepts(target, first) {
    return Some(first)
  }
  match (source, target) {
    (Integer(_, high), Integer(_, limit)) if high > limit => Some(number(high))
    (Text(None), Text(Some(allowed))) => Some(outside_enum(allowed))
    _ => None
  }
}

///|
fn required_record(source : Contract) -> Map[String, Json] {
  let record : Map[String, Json] = Map([])
  for name in source.names {
    let field = source.fields[name]
    if field.required {
      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)
  }
  for name in target.names {
    let next = target.fields[name]
    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) =>
        if difference(field.domain, next.domain) is Some(value) {
          findings.push({
            field: name,
            reason: "narrowed_domain",
            witness: make_witness(Some((name, value))),
          })
        }
      None if source.open =>
        findings.push({
          field: name,
          reason: "previously_unrestricted",
          witness: make_witness(Some((name, Json::null()))),
        })
      None => ()
    }
  }
  if !target.open {
    for name in source.names {
      if !target.fields.contains(name) {
        findings.push({
          field: name,
          reason: "removed_field",
          witness: make_witness(
            Some((name, sample(source.fields[name].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
}