///|
#derive(Debug, Eq)
pub(all) enum Outcome {
  MissingReview
  Responded(ArrayView[Int32])
  NoResponse
  InvalidResponse
}

///|
#derive(Debug, Eq)
pub(all) enum ReviewAction {
  Choose(ArrayView[Int32])
  MarkBlank
  Reject
}

///|
pub struct Decision {
  action : ReviewAction
  note : String
}

///|
pub struct ReviewEvent {
  revision : Int32
  question : Int32
  previous : Decision?
  current : Decision?
}

///|
pub struct Sheet {
  id : String
  scan : Scan
  priv decisions : Map[Int32, Decision]
  priv history : Array[ReviewEvent]
}

///|
fn validate_label(
  value : String,
  max_length : Int32,
  description : String,
) -> Unit raise MarkError {
  if value.length() < 1 || value.length() > max_length {
    raise Invalid("\{description} length is outside the allowed range")
  }
  for character in value {
    if character.to_int() < 32 || character.to_int() == 127 {
      raise Invalid("\{description} contains a control character")
    }
  }
}

///|
pub fn Sheet::new(id : String, scan : Scan) -> Sheet raise MarkError {
  validate_label(id, 128, "sheet ID")
  { id, scan, decisions: Map([]), history: [], }
}

///|
pub fn Sheet::revision(self : Sheet) -> Int32 {
  self.history.length()
}

///|
pub fn Sheet::history(self : Sheet) -> Array[ReviewEvent] {
  self.history.copy()
}

///|
fn Sheet::check_index(self : Sheet, index : Int32) -> Unit raise MarkError {
  if index < 0 || index >= self.scan.readings.length() {
    raise Invalid("question index is outside the sheet")
  }
}

///|
fn canonical_selection(
  question : Question,
  choices : ArrayView[Int32],
) -> ArrayView[Int32] raise MarkError {
  if choices.is_empty() || choices.length() > question.max_marks {
    raise Invalid("review selection must respect the question selection limit")
  }
  let sorted = choices.to_owned()
  sorted.sort()
  for index in 0..= question.options ||
      (index > 0 && sorted[index - 1] == choice) {
      raise Invalid("review selection contains a repeated or unknown option")
    }
  }
  sorted[:]
}

///|
fn Sheet::transition(
  self : Sheet,
  index : Int32,
  current : Decision?,
  expected_revision : Int32,
) -> Unit raise MarkError {
  if self.revision() != expected_revision {
    raise ReviewRequired("the sheet changed since it was opened for review")
  }
  if self.revision() >= 10000 {
    raise Invalid("this sheet has reached the 10000 revision limit")
  }
  let previous = self.decisions.get(index)
  match current {
    Some(decision) => self.decisions[index] = decision
    None => self.decisions.remove(index)
  }
  self.history.push({
    revision: self.revision() + 1,
    question: index,
    previous,
    current,
  })
}

///|
pub fn Sheet::review(
  self : Sheet,
  index : Int32,
  action : ReviewAction,
  note : String,
  expected_revision : Int32,
) -> Unit raise MarkError {
  self.check_index(index)
  validate_label(note, 300, "review note")
  let action = match action {
    Choose(options) =>
      Choose(canonical_selection(self.scan.template.questions[index], options))
    MarkBlank => MarkBlank
    Reject => Reject
  }
  self.transition(index, Some({ action, note, }), expected_revision)
}

///|
pub fn Sheet::reset(
  self : Sheet,
  index : Int32,
  expected_revision : Int32,
) -> Unit raise MarkError {
  self.check_index(index)
  if !self.decisions.contains(index) {
    raise Invalid("this question has no manual decision to remove")
  }
  self.transition(index, None, expected_revision)
}

///|
pub fn Sheet::decision(self : Sheet, index : Int32) -> Decision? {
  self.decisions.get(index)
}

///|
pub fn Sheet::outcome(self : Sheet, index : Int32) -> Outcome raise MarkError {
  self.check_index(index)
  if self.decisions.get(index) is Some(decision) {
    return match decision.action {
      Choose(answers) => Responded(answers)
      MarkBlank => NoResponse
      Reject => InvalidResponse
    }
  }
  let reading = self.scan.readings[index]
  match reading.finding {
    Accepted => Responded(reading.selected)
    Blank => NoResponse
    _ => MissingReview
  }
}

///|
pub fn Sheet::pending(self : Sheet) -> Array[Int32] {
  let pending : Array[Int32] = []
  for reading in self.scan.readings {
    if reading.finding.needs_review() && !self.decisions.contains(reading.index) {
      pending.push(reading.index)
    }
  }
  pending
}

///|
pub struct Batch {
  template : Template
  priv sheets : Map[String, Sheet]
  priv fingerprints : Map[UInt64, String]
  priv serials : Map[Int32, String]
}

///|
pub fn Batch::new(template : Template) -> Batch {
  { template, sheets: Map([]), fingerprints: Map([]), serials: Map([]), }
}

///|
fn same_template(a : Template, b : Template) -> Bool {
  a.title == b.title && a.questions == b.questions
}

///|
pub fn Batch::add(self : Batch, sheet : Sheet) -> Unit raise MarkError {
  if self.sheets.length() >= 1000 {
    raise Invalid("batch exceeds the 1000 sheet limit")
  }
  if !same_template(self.template, sheet.scan.template) {
    raise Invalid("sheet template differs from the batch template")
  }
  if self.sheets.contains(sheet.id) {
    raise Invalid("duplicate sheet ID")
  }
  if self.fingerprints.get(sheet.scan.image_fingerprint) is Some(id) {
    raise Invalid("image already added under sheet ID \{id}")
  }
  if sheet.scan.printed_serial is Some(serial) {
    if self.serials.get(serial) is Some(id) {
      raise Invalid("printed serial \{serial} already appears on sheet \{id}")
    }
    self.serials[serial] = sheet.id
  }
  self.sheets[sheet.id] = sheet
  self.fingerprints[sheet.scan.image_fingerprint] = sheet.id
}

///|
pub fn Batch::get(self : Batch, id : String) -> Sheet? {
  self.sheets.get(id)
}

///|
pub fn Batch::remove(self : Batch, id : String) -> Bool {
  match self.sheets.get(id) {
    Some(sheet) => {
      self.sheets.remove(id)
      self.fingerprints.remove(sheet.scan.image_fingerprint)
      if sheet.scan.printed_serial is Some(serial) {
        self.serials.remove(serial)
      }
      true
    }
    None => false
  }
}

///|
pub fn Batch::ids(self : Batch) -> Array[String] {
  let ids : Array[String] = []
  for id, _ in self.sheets {
    ids.push(id)
  }
  ids.sort()
  ids
}