///|
/// Review coverage trade-offs over already extracted bubble evidence.
pub struct CalibrationCase {
  scan : Scan
  truths : ArrayView[ArrayView[Int32]]
}

///|
pub fn CalibrationCase::new(
  scan : Scan,
  truths : Array[Array[Int32]],
) -> CalibrationCase raise MarkError {
  if truths.length() != scan.template.questions.length() {
    raise Invalid("calibration truth must cover the entire form")
  }
  let canonical : Array[ArrayView[Int32]] = []
  for index in 0.. QuestionReading {
  let options : Array[BubbleReading] = []
  for bubble in reading.bubbles {
    let state = mark_state(bubble.score, bubble.edge_ink, policy)
    options.push({
      option: bubble.option,
      state,
      score: bubble.score,
      dark_fraction: bubble.dark_fraction,
      edge_ink: bubble.edge_ink,
      paper: bubble.paper,
      ring: bubble.ring,
      crop: bubble.crop,
    })
  }
  classify_question(reading.index, options, question, policy)
}

///|
pub fn calibrate(
  cases : Array[CalibrationCase],
  policies : Array[DetectionPolicy],
) -> Array[CalibrationPoint] raise MarkError {
  if cases.is_empty() ||
    cases.length() > 1000 ||
    policies.is_empty() ||
    policies.length() > 100 {
    raise Invalid("calibration needs 1 to 1000 cases and 1 to 100 policies")
  }
  let points : Array[CalibrationPoint] = []
  for policy in policies {
    let mut total = 0
    let mut deferred = 0
    let mut automatic_errors = 0
    let mut missed_marks = 0
    let mut false_marks = 0
    for example in cases {
      for reading in example.scan.readings {
        total += 1
        let question = example.scan.template.questions[reading.index]
        let reproduction = reclassify(reading, question, policy)
        if reproduction.finding.needs_review() {
          deferred += 1
          continue
        }
        let truth = example.truths[reading.index]
        if reproduction.selected != truth {
          automatic_errors += 1
          for option in truth {
            if !reproduction.selected.contains(option) {
              missed_marks += 1
            }
          }
          for option in reproduction.selected {
            if !truth.contains(option) {
              false_marks += 1
            }
          }
        }
      }
    }
    points.push({
      policy,
      counts: { total, deferred, automatic_errors, missed_marks, false_marks, },
    })
  }
  points
}

///|
pub fn CalibrationPoint::json(self : CalibrationPoint) -> Json {
  let result = self.counts
  Json::object(
    Map([
      ("policy", self.policy.json()),
      ("total", jint(result.total)),
      ("deferred", jint(result.deferred)),
      ("automatic_errors", jint(result.automatic_errors)),
      ("missed_marks", jint(result.missed_marks)),
      ("false_marks", jint(result.false_marks)),
      (
        "automatic_error_rate",
        fraction(result.automatic_errors, result.total - result.deferred),
      ),
      ("review_rate", fraction(result.deferred, result.total)),
    ]),
  )
}