///|
pub(all) struct Trial {
  id : String
  source : String
  reference : Array[Row]
  first : Array[Row]
  second : Array[Row]
}

///|
/// Check the trial identifier used in batches and their manifests.
pub fn validate_batch_trial_id(id : String) -> Unit raise AuditError {
  if id.is_blank() ||
    id.contains("\n") ||
    id.contains("\r") ||
    id.contains("\t") {
    raise InvalidInput("invalid batch trial ID")
  }
}

///|
fn total_score(a : Score, b : Score) -> Score {
  {
    reference_keys: a.reference_keys + b.reference_keys,
    correct_keys: a.correct_keys + b.correct_keys,
    issue_count: a.issue_count + b.issue_count,
    bad_reference_keys: a.bad_reference_keys + b.bad_reference_keys,
    extra_keys: a.extra_keys + b.extra_keys,
    correct_unmeasured: a.correct_unmeasured + b.correct_unmeasured,
    correct_true_zero: a.correct_true_zero + b.correct_true_zero,
    unit_equivalent: a.unit_equivalent + b.unit_equivalent,
  }
}

///|
/// Score independent trials. The denominator sums reference keys across
/// trials. A key used in two trials counts once per trial.
fn evaluate_batch(
  trials : Array[Trial],
) -> (Array[(String, Evaluation, Evaluation)], Score, Score) raise AuditError {
  if trials.is_empty() {
    raise InvalidInput("batch must contain at least one trial")
  }
  let ids : Map[String, Bool] = Map([])
  let results : Array[(String, Evaluation, Evaluation)] = []
  let zero : Score = {
    reference_keys: 0,
    correct_keys: 0,
    issue_count: 0,
    bad_reference_keys: 0,
    extra_keys: 0,
    correct_unmeasured: 0,
    correct_true_zero: 0,
    unit_equivalent: 0,
  }
  let mut a_total = zero
  let mut b_total = zero
  for trial in trials {
    validate_batch_trial_id(trial.id)
    if ids.get(trial.id) is Some(_) {
      raise InvalidInput("duplicate batch trial ID: \{trial.id}")
    }
    ids[trial.id] = true
    let (a, b) = (
      evaluate(trial.source, trial.reference, trial.first),
      evaluate(trial.source, trial.reference, trial.second),
    ) catch {
      InvalidInput(message) =>
        raise InvalidInput("trial \{trial.id}: \{message}")
    }
    a_total = total_score(a_total, a.score)
    b_total = total_score(b_total, b.score)
    results.push((trial.id, a, b))
  }
  (results, a_total, b_total)
}

///|
pub fn compare_batch(trials : Array[Trial]) -> String raise AuditError {
  let (results, a_total, b_total) = evaluate_batch(trials)
  let reports : Array[String] = []
  for (id, a, b) in results {
    reports.push("TRIAL \{id}")
    reports.push(render_pair(a, b))
  }
  let delta = b_total.correct_keys - a_total.correct_keys
  reports.push("BATCH trials=\{trials.length()} denominator=sum_reference_keys")
  reports.push(a_total.line("A"))
  reports.push(b_total.line("B"))
  reports.push("DELTA correct=\{delta} denominator=\{a_total.reference_keys}")
  reports.join("\n")
}