///|
#derive(ToJson, Eq, Debug)
pub(all) struct CsvSnapshotRow {
  key : Array[String]
  lines : (Int32, Int32)
  values : Map[String, String]
}

///|
#derive(ToJson, Eq, Debug)
pub(all) struct CsvFieldChange {
  field : String
  before : String
  after : String
}

///|
#derive(ToJson, Eq, Debug)
pub(all) struct CsvChangedRow {
  key : Array[String]
  old_lines : (Int32, Int32)
  new_lines : (Int32, Int32)
  fields : Array[CsvFieldChange]
}

///|
#derive(ToJson, Eq, Debug)
pub(all) struct CsvKeyConflict {
  key : Array[String]
  reason : String
  old_lines : Array[(Int32, Int32)]
  new_lines : Array[(Int32, Int32)]
}

///|
#derive(ToJson, Eq, Debug)
pub(all) struct CsvVersionDiff {
  old_rows : Int32
  new_rows : Int32
  columns_added : Array[String]
  columns_removed : Array[String]
  added : Array[CsvSnapshotRow]
  removed : Array[CsvSnapshotRow]
  changed : Array[CsvChangedRow]
  unchanged : Int32
  conflicts : Array[CsvKeyConflict]
}

///|
priv struct CsvSnapshotIndex {
  input : LookupTable
  by_key : Map[Array[String], Array[Int32]]
}

///|
fn CsvSnapshotIndex::new(
  table : LookupTable,
  columns : Array[String],
) -> Result[CsvSnapshotIndex, String] {
  if columns.is_empty() {
    return Err(table.table.name + ": select at least one key column")
  }
  let positions = match table.positions(columns) {
    Ok(p) => p
    Err(e) => return Err(e)
  }
  let by_key : Map[Array[String], Array[Int32]] = Map([])
  for i, row in table.table.rows {
    let key = positions.map(pos => row[pos])
    match by_key.get(key) {
      Some(group) => group.push(i)
      None => by_key[key] = [i]
    }
  }
  Ok({ input: table, by_key, })
}

///|
fn CsvSnapshotIndex::span(self : CsvSnapshotIndex, i : Int32) -> (Int32, Int32) {
  self.input.spans[i + 1]
}

///|
fn CsvSnapshotIndex::describe_row(
  self : CsvSnapshotIndex,
  key : Array[String],
  i : Int32,
) -> CsvSnapshotRow {
  let values : Map[String, String] = Map([])
  let row = self.input.table.rows[i]
  for j, field in self.input.table.header {
    values[field] = row[j]
  }
  { key, lines: self.span(i), values, }
}

///|
/// Visit aligned keys in component-wise lexical order, independent of CSV or map order.
/// Refuse to pair a duplicate on either side, even when the other side is unique.
fn visit_csv_keys(
  old : CsvSnapshotIndex,
  current : CsvSnapshotIndex,
  visit : (Array[String], Int32?, Int32?) -> Unit,
) -> Array[CsvKeyConflict] {
  let keys = old.by_key.keys().collect()
  for key in current.by_key.keys() {
    if !old.by_key.contains(key) {
      keys.push(key)
    }
  }
  keys.sort_by((a, b) => {
    for i in 0.. 1 || after.length() > 1 {
      conflicts.push({
        key,
        reason: if key.contains("") {
          "empty_key"
        } else {
          "duplicate_key"
        },
        old_lines: before.map(i => old.span(i)),
        new_lines: after.map(i => current.span(i)),
      })
    } else {
      visit(key, before.get(0), after.get(0))
    }
  }
  conflicts
}

///|
/// Compare two UTF-8 CSV snapshots by exact textual key components. Non-key cells
/// are aligned by column name. Added and removed columns are reported separately.
pub fn compare_csv_versions(
  old : LookupTable,
  current : LookupTable,
  keys : Array[String],
) -> Result[CsvVersionDiff, String] {
  let before = match CsvSnapshotIndex::new(old, keys) {
    Ok(index) => index
    Err(e) => return Err(e)
  }
  let after = match CsvSnapshotIndex::new(current, keys) {
    Ok(index) => index
    Err(e) => return Err(e)
  }
  let old_header = old.table.header
  let new_header = current.table.header
  let new_positions : Map[String, Int32] = Map([])
  for i, name in new_header {
    new_positions[name] = i
  }
  let old_names = @hashset.HashSet::from_iter(old_header.iter())
  let columns_added = new_header.filter(name => !old_names.contains(name))
  let columns_removed = old_header.filter(name => !new_positions.contains(name))
  let common : Array[(String, Int32, Int32)] = []
  for i, name in old_header {
    if new_positions.get(name) is Some(j) && !keys.contains(name) {
      common.push((name, i, j))
    }
  }
  common.sort_by((a, b) => a.0.lexical_compare(b.0))
  columns_added.sort_by((a, b) => a.lexical_compare(b))
  columns_removed.sort_by((a, b) => a.lexical_compare(b))
  let added = []
  let removed = []
  let changed = []
  let mut unchanged = 0
  let conflicts = visit_csv_keys(before, after, (key, i, j) => {
    match (i, j) {
      (Some(i), Some(j)) => {
        let fields = []
        for (name, col1, col2) in common {
          let left = old.table.rows[i][col1]
          let right = current.table.rows[j][col2]
          if left != right {
            fields.push({ field: name, before: left, after: right, })
          }
        }
        if fields.is_empty() {
          unchanged += 1
        } else {
          changed.push({
            key,
            old_lines: before.span(i),
            new_lines: after.span(j),
            fields,
          })
        }
      }
      (Some(i), None) => removed.push(before.describe_row(key, i))
      (None, Some(j)) => added.push(after.describe_row(key, j))
      (None, None) => ()
    }
  })
  Ok({
    old_rows: old.table.rows.length(),
    new_rows: current.table.rows.length(),
    columns_added,
    columns_removed,
    added,
    removed,
    changed,
    unchanged,
    conflicts,
  })
}

///|
pub fn CsvVersionDiff::is_clean(self : CsvVersionDiff) -> Bool {
  self.conflicts.is_empty()
}