///|
/// Two-way crossed interaction mean square in mm² for balanced designs.
pub fn interaction_ms(rows : Array[Row]) -> Double? {
  match analyze_interaction(rows) {
    Ok(value) => Some(value)
    Err(_) => None
  }
}

///|
priv enum InteractionIssue {
  EmptyRows
  Unmeasured(Row)
  DuplicateRepeat(Row)
  TooFewLevels(Int32, Int32)
  MissingCrossing(String, String)
  RepeatSetMismatch(String, String, Row, Array[String], Array[String])
  TooFewRepeats(Row, Int32)
  ContrastOutOfRange(String, String, String)
  CellTotalOutOfRange(String, String)
  UnderflowMeanSquare
  NonfiniteMeanSquare
}

///|
fn repeat_ids(cell : Map[String, DecimalReading]) -> Array[String] {
  let ids : Array[String] = []
  for id, _ in cell {
    ids.push(id)
  }
  ids
}

///|
fn analyze_interaction(rows : Array[Row]) -> Result[Double, InteractionIssue] {
  if rows.is_empty() {
    return Err(EmptyRows)
  }
  let ordered = rows.copy()
  ordered.sort_by(fn(a, b) { a.key().compare(b.key()) })
  let first = ordered[0]
  let part_totals : Map[String, Double] = Map([])
  let operator_totals : Map[String, Double] = Map([])
  let cells : Map[String, Map[String, DecimalReading]] = Map([])
  for row in ordered {
    guard row.exact_mm is Some(mm) else { return Err(Unmeasured(row)) }
    let key = "\{row.part}|\{row.operator}"
    let cell = match cells.get(key) {
      Some(cell) => cell
      None => {
        let cell : Map[String, DecimalReading] = Map([])
        cells[key] = cell
        cell
      }
    }
    if cell.get(row.repeat) is Some(_) {
      return Err(DuplicateRepeat(row))
    }
    cell[row.repeat] = mm
    part_totals[row.part] = 0.0
    operator_totals[row.operator] = 0.0
  }
  let p = part_totals.length()
  let o = operator_totals.length()
  if p < 2 || o < 2 {
    return Err(TooFewLevels(p, o))
  }
  if cells.length() != p * o {
    for part, _ in part_totals {
      for operator, _ in operator_totals {
        if cells.get("\{part}|\{operator}") is None {
          return Err(MissingCrossing(part, operator))
        }
      }
    }
  }
  let template = cells["\{first.part}|\{first.operator}"]
  let repeats = template.length()
  for part, _ in part_totals {
    for operator, _ in operator_totals {
      let cell = cells["\{part}|\{operator}"]
      if cell.length() != repeats {
        return Err(
          RepeatSetMismatch(
            part,
            operator,
            first,
            repeat_ids(template),
            repeat_ids(cell),
          ),
        )
      }
      for rep, _ in cell {
        if template.get(rep) is None {
          return Err(
            RepeatSetMismatch(
              part,
              operator,
              first,
              repeat_ids(template),
              repeat_ids(cell),
            ),
          )
        }
      }
    }
  }
  if repeats < 2 {
    return Err(TooFewRepeats(first, repeats))
  }
  let centered_cells : Array[(String, String, Double)] = []
  for part, _ in part_totals {
    let part_anchor = cells["\{part}|\{first.operator}"]
    for operator, _ in operator_totals {
      let operator_anchor = cells["\{first.part}|\{operator}"]
      let cell = cells["\{part}|\{operator}"]
      let contrasts : Array[DecimalReading] = []
      for rep, value in cell {
        guard decimal_sum([
            value,
            part_anchor[rep].opposite(),
            operator_anchor[rep].opposite(),
            template[rep],
          ])
          is Some(contrast) else {
          return Err(ContrastOutOfRange(part, operator, rep))
        }
        contrasts.push(contrast)
      }
      guard decimal_sum(contrasts).bind(fn(value) { value.to_finite_double() })
        is Some(cell_total) else {
        return Err(CellTotalOutOfRange(part, operator))
      }
      centered_cells.push((part, operator, cell_total))
    }
  }
  let mut total = 0.0
  for (part, operator, cell_total) in centered_cells {
    part_totals[part] = part_totals[part] + cell_total
    operator_totals[operator] = operator_totals[operator] + cell_total
    total += cell_total
  }
  let grand = total / rows.length().to_double()
  let mut sum = 0.0
  let mut nonzero_residual = false
  for (part, operator, cell_total) in centered_cells {
    let residual = cell_total / repeats.to_double() -
      part_totals[part] / (o * repeats).to_double() -
      operator_totals[operator] / (p * repeats).to_double() +
      grand
    sum += residual * residual
    if residual != 0.0 {
      nonzero_residual = true
    }
  }
  let mean_square = repeats.to_double() * sum / ((p - 1) * (o - 1)).to_double()
  if mean_square == 0.0 && nonzero_residual {
    Err(UnderflowMeanSquare)
  } else if mean_square.is_finite() {
    Ok(mean_square)
  } else {
    Err(NonfiniteMeanSquare)
  }
}