///|
/// One named cell from an added or removed record.
#derive(Eq, Debug, ToJson)
pub struct Cell {
  column : String
  value : String
}

///|
/// A complete record and its key in the configured column order.
#derive(Eq, Debug, ToJson)
pub struct Record {
  key : Array[String]
  cells : Array[Cell]
}

///|
/// Old and new values for a common non-key column on a matched record.
#derive(Eq, Debug, ToJson)
pub struct CellChange {
  column : String
  before : String
  after : String
}

///|
#derive(Eq, Debug, ToJson)
pub struct RecordChange {
  key : Array[String]
  cells : Array[CellChange]
}

///|
/// Reconciliation result. Ordering is independent of input layout.
#derive(Eq, Debug, ToJson)
pub struct Report {
  key_columns : Array[String]
  baseline_columns : Array[String]
  candidate_columns : Array[String]
  added_columns : Array[String]
  removed_columns : Array[String]
  added_rows : Array[Record]
  removed_rows : Array[Record]
  changed_rows : Array[RecordChange]
  unchanged_rows : Int32
}

///|
fn Snapshot::sorted_columns(self : Snapshot) -> Array[(String, Int32)] {
  let columns = self.columns.iter().collect()
  columns.sort_by((left, right) => left.0[:].lexical_compare(right.0[:]))
  columns
}

///|
fn KeyedRow::to_record(
  self : KeyedRow,
  columns : Array[(String, Int32)],
) -> Record {
  let cells = columns.map(column => {
    column: column.0,
    value: self.record.cells[column.1],
  })
  { key: self.key, cells, }
}

///|
/// Compare headered CSV snapshots by a caller-supplied ordered key.
pub fn reconcile(
  baseline : String,
  candidate : String,
  keys : Array[String],
) -> Result[Report, Issue] {
  if validate_keys(keys) is Err(error) {
    return Err(error)
  }
  let before = match prepare_snapshot(baseline, keys, "baseline") {
    Ok(snapshot) => snapshot
    Err(error) => return Err(error)
  }
  let before_rows = match before.index_rows("baseline") {
    Ok(rows) => rows
    Err(error) => return Err(error)
  }
  let after = match prepare_snapshot(candidate, keys, "candidate") {
    Ok(snapshot) => snapshot
    Err(error) => return Err(error)
  }
  let after_rows = match after.index_rows("candidate") {
    Ok(rows) => rows
    Err(error) => return Err(error)
  }
  let before_columns = before.sorted_columns()
  let after_columns = after.sorted_columns()
  let added_columns = after_columns.filter_map(column => {
    if before.columns.contains(column.0) {
      None
    } else {
      Some(column.0)
    }
  })
  let removed_columns = before_columns.filter_map(column => {
    if after.columns.contains(column.0) {
      None
    } else {
      Some(column.0)
    }
  })
  let common_columns = before_columns.filter_map(column => {
    let (name, before_index) = column
    match after.columns.get(name) {
      Some(after_index) if !keys.contains(name) =>
        Some((name, before_index, after_index))
      _ => None
    }
  })
  let added_rows = []
  let removed_rows = []
  let changed_rows : Array[RecordChange] = []
  let mut unchanged_rows = 0
  let mut old_index = 0
  let mut new_index = 0
  while old_index < before_rows.length() && new_index < after_rows.length() {
    let old = before_rows[old_index]
    let new = after_rows[new_index]
    let order = compare_keys(old.key, new.key)
    if order < 0 {
      removed_rows.push(old.to_record(before_columns))
      old_index += 1
    } else if order > 0 {
      added_rows.push(new.to_record(after_columns))
      new_index += 1
    } else {
      let cells = common_columns.filter_map(column => {
        let (name, from, to) = column
        let old_value = old.record.cells[from]
        let new_value = new.record.cells[to]
        if old_value == new_value {
          None
        } else {
          Some({ column: name, before: old_value, after: new_value, })
        }
      })
      if cells.is_empty() {
        unchanged_rows += 1
      } else {
        changed_rows.push({ key: old.key, cells, })
      }
      old_index += 1
      new_index += 1
    }
  }
  for index in old_index.. column.0),
    candidate_columns: after_columns.map(column => column.0),
    added_columns,
    removed_columns,
    added_rows,
    removed_rows,
    changed_rows,
    unchanged_rows,
  })
}