///|
pub struct KeyItem {
  correct : ArrayView[Int32]
  points : Int32
}

///|
pub struct AnswerKey {
  template : Template
  items : ArrayView[KeyItem]
  maximum : Int32
}

///|
#derive(Debug, Eq)
pub(all) enum ResultKind {
  Correct
  Incorrect
  Unanswered
  Disqualified
}

///|
#derive(Debug, Eq)
pub(all) struct ItemGrade {
  question : Int32
  kind : ResultKind
  awarded : Int32
  possible : Int32
}

///|
pub struct Grade {
  sheet_id : String
  points : Int32
  maximum : Int32
  results : ArrayView[ItemGrade]
}

///|
pub fn AnswerKey::new(
  template : Template,
  answers : Array[Array[Int32]],
  points : Array[Int32],
) -> AnswerKey raise MarkError {
  if answers.length() != template.questions.length() ||
    points.length() != template.questions.length() {
    raise Invalid("answer key must cover every question in the template")
  }
  let items : Array[KeyItem] = []
  let mut maximum = 0
  for index in 0.. 10000 {
      raise Invalid("answer key points must be between 1 and 10000")
    }
    maximum += weight
    items.push({ correct, points: weight, })
  }
  { template, items: items[:], maximum, }
}

///|
pub fn AnswerKey::from_json(
  template : Template,
  value : Json,
) -> AnswerKey raise MarkError {
  let fields = json_object(value, "answer key")
  assert_version(fields)
  let answers = truth_from_json(required(fields, "answers"))
  let weights = json_ints(required(fields, "points"), "points")
  AnswerKey::new(template, answers, weights)
}

///|
pub fn AnswerKey::json(self : AnswerKey) -> Json {
  let answers : Array[Json] = []
  let points : Array[Json] = []
  for item in self.items {
    answers.push(jints(item.correct))
    points.push(jint(item.points))
  }
  Json::object(
    Map([
      ("version", jint(1)),
      ("answers", Json::array(answers)),
      ("points", Json::array(points)),
    ]),
  )
}

///|
pub fn AnswerKey::grade(
  self : AnswerKey,
  sheet : Sheet,
) -> Grade raise MarkError {
  if !same_template(self.template, sheet.scan.template) {
    raise Invalid("answer key and sheet templates differ")
  }
  let results : Array[ItemGrade] = []
  let mut points = 0
  for index in 0..
        if options == item.correct {
          Correct
        } else {
          Incorrect
        }
      NoResponse => Unanswered
      InvalidResponse => Disqualified
      MissingReview =>
        raise ReviewRequired(
          "sheet \{sheet.id}, question \{index + 1} must be reviewed before grading",
        )
    }
    let awarded = if kind == Correct { item.points } else { 0 }
    points += awarded
    results.push({ question: index, kind, awarded, possible: item.points, })
  }
  { sheet_id: sheet.id, points, maximum: self.maximum, results: results[:], }
}

///|
fn result_kind(kind : ResultKind) -> String {
  match kind {
    Correct => "correct"
    Incorrect => "incorrect"
    Unanswered => "unanswered"
    Disqualified => "invalid"
  }
}

///|
pub fn Grade::json(self : Grade) -> Json {
  let results : Array[Json] = []
  for result in self.results {
    results.push(
      Json::object(
        Map([
          ("question", jint(result.question)),
          ("status", Json::string(result_kind(result.kind))),
          ("awarded", jint(result.awarded)),
          ("possible", jint(result.possible)),
        ]),
      ),
    )
  }
  Json::object(
    Map([
      ("sheet_id", Json::string(self.sheet_id)),
      ("points", jint(self.points)),
      ("maximum", jint(self.maximum)),
      ("items", Json::array(results)),
    ]),
  )
}

///|
pub fn AnswerKey::batch_grades(
  self : AnswerKey,
  batch : Batch,
) -> Array[Grade] raise MarkError {
  if !same_template(self.template, batch.template) {
    raise Invalid("answer key and batch templates differ")
  }
  let grades : Array[Grade] = []
  for id in batch.ids() {
    grades.push(self.grade(batch.get(id).unwrap()))
  }
  grades
}

///|
pub fn grades_csv(grades : Array[Grade]) -> String {
  let out = StringBuilder()
  out.write_string("sheet_id,points,maximum\r\n")
  for grade in grades {
    out.write_string(
      "\{csv_text(grade.sheet_id)},\{grade.points},\{grade.maximum}\r\n",
    )
  }
  out.to_string()
}