///|
/// Release constraints applied to one reconciliation report.
pub struct Gate {
  max_added : Int32?
  max_removed : Int32?
  max_changed : Int32?
  except_from_limit : Array[String]
  require_same_columns : Bool
  protected_columns : Array[String]
}

///|
pub fn Gate::new(
  max_added? : Int32,
  max_removed? : Int32,
  max_changed? : Int32,
  except_from_limit~ : Array[String] = [],
  require_same_columns~ : Bool = false,
  protected_columns~ : Array[String] = [],
) -> Gate {
  {
    max_added,
    max_removed,
    max_changed,
    except_from_limit: except_from_limit.copy(),
    require_same_columns,
    protected_columns: protected_columns.copy(),
  }
}

///|
#derive(Eq, Debug, ToJson)
pub struct Violation {
  code : String
  column : String?
  observed : Int32
  limit : Int32
}

///|
#derive(Eq, Debug, ToJson)
pub struct Decision {
  passed : Bool
  violations : Array[Violation]
}

///|
/// Count matched records with a change outside the named columns.
pub fn Report::count_changed_except(
  self : Report,
  columns : Array[String],
) -> Int32 {
  if columns.is_empty() {
    return self.changed_rows.length()
  }
  let excluded = Set::from_array(columns)
  self.changed_rows
  .iter()
  .filter(row => row.cells.iter().any(cell => !excluded.contains(cell.column)))
  .count()
}

///|
/// Evaluate the release gate. Configuration errors are distinct from failures.
pub fn Gate::evaluate(self : Gate, report : Report) -> Result[Decision, Issue] {
  if !self.except_from_limit.is_empty() && self.max_changed is None {
    return Err(
      issue(
        "missing-change-limit", "configuration", "--except-from-limit requires --max-changed.",
      ),
    )
  }
  let seen : Set[String] = Set([])
  for column in self.except_from_limit {
    if report.key_columns.contains(column) ||
      !report.baseline_columns.contains(column) ||
      !report.candidate_columns.contains(column) {
      return Err(
        issue(
          "invalid-exempt-column",
          "configuration",
          "Change-limit exemption must name a shared non-key column: \{Json::string(column).stringify()}.",
        ),
      )
    }
    if seen.contains(column) {
      return Err(
        issue(
          "duplicate-exempt-column",
          "configuration",
          "Repeated change-limit exemption: \{Json::string(column).stringify()}.",
        ),
      )
    }
    seen.insert(column)
  }
  let limits = [
    ("too-many-additions", self.max_added, report.added_rows.length()),
    ("too-many-removals", self.max_removed, report.removed_rows.length()),
    (
      "too-many-changes",
      self.max_changed,
      report.count_changed_except(self.except_from_limit),
    ),
  ]
  let violations = []
  for limit_rule in limits {
    let (code, maximum, observed) = limit_rule
    if maximum is Some(limit) {
      if limit < 0 {
        return Err(
          issue(
            "invalid-limit", "configuration", "Row limits must be nonnegative.",
          ),
        )
      }
      if observed > limit {
        violations.push({ code, column: None, observed, limit, })
      }
    }
  }
  let schema_changes = report.added_columns.length() +
    report.removed_columns.length()
  if self.require_same_columns && schema_changes > 0 {
    violations.push({
      code: "schema-changed",
      column: None,
      observed: schema_changes,
      limit: 0,
    })
  }
  let counts : Map[String, Int32] = Map([])
  let sorted_protected = self.protected_columns.copy()
  sorted_protected.sort_by((left, right) => left[:].lexical_compare(right[:]))
  for column in sorted_protected {
    let quoted = Json::string(column).stringify()
    if !report.baseline_columns.contains(column) ||
      report.key_columns.contains(column) {
      return Err(
        issue(
          "invalid-protected-column",
          "configuration",
          "Protected column \{quoted} must be a non-key baseline column.",
        ),
      )
    }
    if counts.contains(column) {
      return Err(
        issue(
          "duplicate-protected-column",
          "configuration",
          "Protected column \{quoted} was specified more than once.",
        ),
      )
    }
    counts[column] = 0
  }
  if !sorted_protected.is_empty() {
    for row in report.changed_rows {
      for cell in row.cells {
        if counts.get(cell.column) is Some(count) {
          counts[cell.column] = count + 1
        }
      }
    }
  }
  for column in sorted_protected {
    if !report.candidate_columns.contains(column) {
      violations.push({
        code: "protected-column-removed",
        column: Some(column),
        observed: 1,
        limit: 0,
      })
    } else if counts[column] > 0 {
      violations.push({
        code: "protected-column-changed",
        column: Some(column),
        observed: counts[column],
        limit: 0,
      })
    }
  }
  Ok({ passed: violations.is_empty(), violations, })
}