///|
/// One pass over a snapshot. Only exact text keys and their counts survive a feed.
pub struct GroupCountAccumulator {
  priv resource : String
  priv group_by : Array[String]
  priv positions : Array[Int32]
  priv width : Int32
  priv counts : Map[Array[String], Int32]
  priv mut rows : Int32
  priv mut error : String?
}

///|
pub fn GroupCountAccumulator::new(
  resource : String,
  header : Array[String],
  group_by : Array[String],
) -> Result[GroupCountAccumulator, String] {
  let columns : Map[String, Int32] = {}
  for i, name in header {
    if name.trim().is_empty() || columns.contains(name) {
      return Err(resource + ": empty or repeated column name")
    }
    columns[name] = i
  }
  if group_by.is_empty() {
    return Err(resource + ": select at least one grouping column")
  }
  let positions = []
  for name in group_by {
    match columns.get(name) {
      Some(i) if !positions.contains(i) => positions.push(i)
      _ =>
        return Err(resource + ": unknown or repeated grouping column: " + name)
    }
  }
  Ok({
    resource,
    group_by: group_by.copy(),
    positions,
    width: header.length(),
    counts: {},
    rows: 0,
    error: None,
  })
}

///|
/// Feed one decoded data record. A failure invalidates the snapshot, even if a
/// caller ignores the return value. Optional physical lines include the header.
pub fn GroupCountAccumulator::feed(
  self : GroupCountAccumulator,
  row : Array[String],
  start_line? : Int32,
  end_line? : Int32,
) -> Result[Unit, String] {
  if self.error is Some(message) {
    return Err(message)
  }
  if self.rows == 2147483647 {
    let message = self.resource + ": too many records for a 32-bit row count"
    self.error = Some(message)
    return Err(message)
  }
  let key = []
  let issue = if row.length() != self.width {
    Some("unexpected number of columns")
  } else {
    for i, pos in self.positions {
      if row[pos].is_empty() {
        break Some("empty grouping column " + self.group_by[i])
      }
      key.push(row[pos])
    } nobreak {
      None
    }
  }
  if issue is Some(issue) {
    let span = match (start_line, end_line) {
      (Some(start), Some(end)) if end != start => " (CSV lines \{start}-\{end})"
      (Some(start), _) => " (CSV line \{start})"
      _ => ""
    }
    let message = "\{self.resource}: data row \{self.rows + 1}\{span}: \{issue}"
    self.error = Some(message)
    return Err(message)
  }
  self.rows += 1
  self.counts[key] = self.counts.get(key).unwrap_or(0) + 1
  Ok(())
}

///|
#derive(Eq, Debug, ToJson)
pub(all) struct GroupCountChange {
  key : Array[String]
  kind : String
  old_count : Int32
  new_count : Int32
  delta : Int32
  alert : Bool
}

///|
#derive(Eq, Debug, ToJson)
pub(all) struct GroupCountReport {
  group_by : Array[String]
  min_loss : Int32
  min_percent : Int32
  old_rows : Int32
  new_rows : Int32
  old_groups : Int32
  new_groups : Int32
  unchanged_groups : Int32
  alert_count : Int32
  changes : Array[GroupCountChange]
}

///|
pub fn GroupCountReport::is_clean(self : GroupCountReport) -> Bool {
  self.alert_count == 0
}

///|
/// Compare two complete group-count snapshots. Percentage thresholds are inclusive
/// and relative to the old count. Losses under either threshold remain in changes.
pub fn compare_group_counts(
  before : GroupCountAccumulator,
  after : GroupCountAccumulator,
  min_loss~ : Int32 = 1,
  min_percent~ : Int32 = 0,
) -> Result[GroupCountReport, String] {
  if min_loss < 1 || min_percent < 0 || min_percent > 100 {
    return Err("Expected min_loss >= 1 and min_percent between 0 and 100")
  }
  for snapshot in [before, after] {
    if snapshot.error is Some(message) {
      return Err(message)
    }
  }
  if before.group_by != after.group_by {
    return Err("Both snapshots must use the same ordered grouping columns")
  }
  let changes = []
  let mut unchanged_groups = 0
  let mut alert_count = 0
  for key, old_count in before.counts {
    let new_count = after.counts.get(key).unwrap_or(0)
    let delta = new_count - old_count
    if delta == 0 {
      unchanged_groups += 1
      continue
    }
    let kind = if new_count == 0 {
      "disappeared"
    } else if delta < 0 {
      "decreased"
    } else {
      "increased"
    }
    let loss = old_count - new_count
    let alert = loss >= min_loss &&
      loss.to_int64() * 100L >= old_count.to_int64() * min_percent.to_int64()
    if alert {
      alert_count += 1
    }
    changes.push({ key: key.copy(), kind, old_count, new_count, delta, alert, })
  }
  for key, new_count in after.counts {
    if !before.counts.contains(key) {
      changes.push({
        key: key.copy(),
        kind: "added",
        old_count: 0,
        new_count,
        delta: new_count,
        alert: false,
      })
    }
  }
  changes.sort_by((left, right) => {
    for i in 0..