///|
fn interaction_cell(part : String, operator : String) -> Json {
  Json::object({
    "part": Json::string(part),
    "operator": Json::string(operator),
  })
}

///|
fn interaction_row_issue(code : String, row : Row) -> Json {
  Json::object({
    "code": Json::string(code),
    "part": Json::string(row.part),
    "operator": Json::string(row.operator),
    "repeat": Json::string(row.repeat),
    "source_line": if row.source_line > 0 {
      Json::number(row.source_line.to_double())
    } else {
      Json::null()
    },
  })
}

///|
fn InteractionIssue::as_json(self : InteractionIssue) -> Json {
  match self {
    EmptyRows => Json::object({ "code": Json::string("EMPTY_ROWS") })
    Unmeasured(row) => interaction_row_issue("UNMEASURED", row)
    DuplicateRepeat(row) => interaction_row_issue("DUPLICATE_REPEAT", row)
    TooFewLevels(parts, operators) =>
      Json::object({
        "code": Json::string("TOO_FEW_LEVELS"),
        "parts": Json::number(parts.to_double()),
        "operators": Json::number(operators.to_double()),
      })
    MissingCrossing(part, operator) =>
      Json::object({
        "code": Json::string("MISSING_CROSSING"),
        "cell": interaction_cell(part, operator),
      })
    RepeatSetMismatch(part, operator, template, expected, actual) =>
      Json::object({
        "code": Json::string("REPEAT_SET_MISMATCH"),
        "cell": interaction_cell(part, operator),
        "template_cell": interaction_cell(template.part, template.operator),
        "expected_repeats": Json::array(expected.map(Json::string)),
        "actual_repeats": Json::array(actual.map(Json::string)),
      })
    TooFewRepeats(row, repeats) =>
      Json::object({
        "code": Json::string("TOO_FEW_REPEATS"),
        "cell": interaction_cell(row.part, row.operator),
        "repeats": Json::number(repeats.to_double()),
      })
    NonfiniteMeanSquare =>
      Json::object({ "code": Json::string("NONFINITE_MEAN_SQUARE") })
    UnderflowMeanSquare =>
      Json::object({ "code": Json::string("UNDERFLOW_MEAN_SQUARE") })
    ContrastOutOfRange(part, operator, repeat) =>
      Json::object({
        "code": Json::string("CONTRAST_OUT_OF_RANGE"),
        "cell": interaction_cell(part, operator),
        "repeat": Json::string(repeat),
      })
    CellTotalOutOfRange(part, operator) =>
      Json::object({
        "code": Json::string("CELL_TOTAL_OUT_OF_RANGE"),
        "cell": interaction_cell(part, operator),
      })
  }
}

///|
fn interaction_side(result : Result[Double, InteractionIssue]) -> Json {
  let (value, issue) = match result {
    Ok(value) => (Json::number(value), Json::null())
    Err(issue) => (Json::null(), issue.as_json())
  }
  Json::object({ "mean_square": value, "issue": issue })
}

///|
/// Explain why a pair can or cannot be compared, with each side's first
/// design or numeric blocker and any key mismatches from normal scoring.
pub fn explain_interaction(
  source : String,
  reference : Array[Row],
  candidate : Array[Row],
) -> Json raise AuditError {
  let evaluation = evaluate(source, reference, candidate)
  let key_problems = evaluation.findings.filter(fn(f) {
    f.blocks_interaction_comparison()
  })
  let (a, b) = match evaluation.interaction {
    Some((a, b)) => (Ok(a), Ok(b))
    None => (analyze_interaction(reference), analyze_interaction(candidate))
  }
  Json::object({
    "schema_version": Json::number(1.0),
    "comparable": Json::boolean(evaluation.interaction is Some(_)),
    "unit": Json::string("mm^2"),
    "comparison_issue": if key_problems.is_empty() {
      Json::null()
    } else {
      Json::object({
        "code": Json::string("KEY_MISMATCH"),
        "findings": Json::array(key_problems.map(fn(f) { f.as_json() })),
      })
    },
    "reference": interaction_side(a),
    "candidate": interaction_side(b),
  })
}