///|
#derive(ToJson, Eq, Debug)
pub(all) struct ImpactExample {
  diagnostic : Diagnostic
  lines : (Int32, Int32)?
}

///|
/// Counts classify distinct records. Each sample contains a diagnostic from the rejecting schema.
#derive(ToJson, Eq, Debug)
pub(all) struct ImpactSummary {
  rows : Int32
  accepted_by_both : Int32
  invalid_in_both : Int32
  newly_invalid : Int32
  newly_valid : Int32
  regressions : Array[ImpactExample]
  recoveries : Array[ImpactExample]
}

///|
priv struct ImpactTally {
  origins : Map[Int32, (Int32, Int32)]
  mut accepted : Int32
  mut rejected : Int32
  mut newly_invalid : Int32
  mut newly_valid : Int32
  regressions : Array[ImpactExample]
  recoveries : Array[ImpactExample]
}

///|
pub struct SchemaImpact {
  priv before : RowValidator
  priv after : RowValidator
  priv limit : Int32
  priv tallies : Array[ImpactTally]
}

///|
pub fn SchemaImpact::new(
  name : String,
  before : TableSchema,
  after : TableSchema,
  header : Array[String],
  max_examples~ : Int32 = 10,
) -> Result[SchemaImpact, Array[Diagnostic]] {
  if max_examples < 0 {
    return Err([issue("input", name, 0, "", "max_examples must be nonnegative")])
  }
  let old = match
    RowValidator::create(name, before, header, 0, max_examples > 0) {
    Ok(v) => v
    Err(errors) =>
      return Err(errors.map(e => { ..e, message: "old schema: " + e.message, }))
  }
  let current = match
    RowValidator::create(name, after, header, 0, max_examples > 0) {
    Ok(v) => v
    Err(errors) =>
      return Err(errors.map(e => { ..e, message: "new schema: " + e.message, }))
  }
  Ok({
    before: old,
    after: current,
    limit: max_examples,
    tallies: Array::makei(4, _ => {
      origins: {},
      accepted: 0,
      rejected: 0,
      newly_invalid: 0,
      newly_valid: 0,
      regressions: [],
      recoveries: [],
    }),
  })
}

///|
fn ErrorSample::at_row(self : ErrorSample, row : Int32) -> Diagnostic? {
  match self.latest {
    Some(e) if e.row == row => Some(e)
    _ => None
  }
}

///|
/// Feed a decoded record once. Optional physical lines come from the caller's CSV decoder.
pub fn SchemaImpact::feed(
  self : SchemaImpact,
  row : Array[String],
  lines? : (Int32, Int32),
) -> Unit {
  self.before.feed_at(row, lines)
  self.after.feed_at(row, lines)
  let n = self.before.rows
  let old_field = self.before.field_errors.at_row(n)
  let new_field = self.after.field_errors.at_row(n)
  let old_key = self.before.key_errors.at_row(n)
  let new_key = self.after.key_errors.at_row(n)
  // Each side can suppress its key diagnostics if a later field fails.
  // Retain the four possible final counts and capped examples in input order.
  for mode, tally in self.tallies {
    let old = if (mode & 1) != 0 && old_field is None {
      old_key
    } else {
      old_field
    }
    let current = if (mode & 2) != 0 && new_field is None {
      new_key
    } else {
      new_field
    }
    match (old, current) {
      (None, None) => tally.accepted += 1
      (Some(_), Some(_)) => tally.rejected += 1
      (None, Some(diagnostic)) => {
        tally.newly_invalid += 1
        if tally.regressions.length() < self.limit {
          tally.regressions.push({ diagnostic, lines, })
          tally.remember_origin(self.after, diagnostic)
        }
      }
      (Some(diagnostic), None) => {
        tally.newly_valid += 1
        if tally.recoveries.length() < self.limit {
          tally.recoveries.push({ diagnostic, lines, })
          tally.remember_origin(self.before, diagnostic)
        }
      }
    }
  }
}

///|
fn ImpactTally::remember_origin(
  self : ImpactTally,
  validator : RowValidator,
  d : Diagnostic,
) -> Unit {
  let first = match d.code {
    "unique" => validator.unique_origin
    "primary-key-duplicate" => validator.key_origin
    _ => None
  }
  if first is Some(span) {
    self.origins[d.row] = span
  }
}

///|
fn SchemaImpact::current_tally(self : SchemaImpact) -> ImpactTally {
  let old_keys = if self.before.field_errors.count == 0 { 1 } else { 0 }
  let new_keys = if self.after.field_errors.count == 0 { 2 } else { 0 }
  self.tallies[old_keys + new_keys]
}

///|
/// First physical CSV lines for a sampled duplicate record in the current impact
/// report. Absent for other diagnostics and when the caller supplied no first span.
pub fn SchemaImpact::first_occurrence_lines(
  self : SchemaImpact,
  row : Int32,
) -> (Int32, Int32)? {
  self.current_tally().origins.get(row)
}

///|
/// Return an independent snapshot with the same key-error precedence as batch validation.
pub fn SchemaImpact::finish(self : SchemaImpact) -> ImpactSummary {
  let t = self.current_tally()
  {
    rows: self.before.rows,
    accepted_by_both: t.accepted,
    invalid_in_both: t.rejected,
    newly_invalid: t.newly_invalid,
    newly_valid: t.newly_valid,
    regressions: t.regressions.copy(),
    recoveries: t.recoveries.copy(),
  }
}