///|
fn finding_text(finding : Finding) -> String {
  match finding {
    Accepted => "accepted"
    Blank => "blank"
    Ambiguous => "ambiguous"
    TooMany => "too_many"
    PoorImage => "poor_image"
  }
}

///|
fn mark_text(state : MarkState) -> String {
  match state {
    Clear => "clear"
    Possible => "possible"
    Filled => "filled"
  }
}

///|
fn csv_text(value : String) -> String {
  let output = StringBuilder()
  output.write_char('"')
  // User-provided text is emitted as spreadsheet text, including after
  // leading spaces. Quotes alone do not prevent formula interpretation.
  for character in value {
    if character == ' ' {
      continue
    }
    if "=+-@".contains(character.to_string()) {
      output.write_char('\'')
    }
    break
  }
  for character in value {
    if character == '"' {
      output.write_char('"')
    }
    output.write_char(character)
  }
  output.write_char('"')
  output.to_string()
}

///|
fn render_answers(answers : ArrayView[Int32]) -> String {
  let output = StringBuilder()
  for i in 0.. Unit raise MarkError {
  let id = csv_text(sheet.id)
  for reading in sheet.scan.readings {
    let index = reading.index
    let (state, options) = match sheet.outcome(index) {
      MissingReview => {
        if !allow_pending {
          raise ReviewRequired("sheet \{sheet.id} has unresolved questions")
        }
        ("pending", "")
      }
      Responded(answers) => ("answered", render_answers(answers))
      NoResponse => ("blank", "")
      InvalidResponse => ("invalid", "")
    }
    let source = if sheet.decision(index) is Some(_) {
      "manual"
    } else {
      "automatic"
    }
    let note = match sheet.decision(index) {
      Some(decision) => decision.note
      None => ""
    }
    let original = finding_text(reading.finding)
    let serial = sheet.scan.printed_serial
      .map(value => value.to_string())
      .unwrap_or("")
    output.write_string(
      "\{id},\{index + 1},\{state},\{options},\{source},\{original},\{csv_text(note)},\{serial}\r\n",
    )
  }
}

///|
const CSV_HEADER : String = "sheet_id,question,status,options,source,original_finding,note,printed_serial\r\n"

///|
pub fn Sheet::csv(
  self : Sheet,
  allow_pending~ : Bool = false,
) -> String raise MarkError {
  let output = StringBuilder()
  output.write_string(CSV_HEADER)
  append_sheet_csv(output, self, allow_pending)
  output.to_string()
}

///|
pub fn Batch::csv(
  self : Batch,
  allow_pending~ : Bool = false,
) -> String raise MarkError {
  let output = StringBuilder()
  output.write_string(CSV_HEADER)
  for id in self.ids() {
    append_sheet_csv(output, self.get(id).unwrap(), allow_pending)
  }
  output.to_string()
}

///|
#derive(Debug, Eq)
pub(all) struct BatchSummary {
  sheets : Int32
  answered : Int32
  blank : Int32
  invalid : Int32
  pending : Int32
  manually_reviewed : Int32
}

///|
pub fn Batch::summary(self : Batch) -> BatchSummary {
  let mut answered = 0
  let mut blank = 0
  let mut invalid = 0
  let mut pending = 0
  let mut manually_reviewed = 0
  for _, sheet in self.sheets {
    manually_reviewed += sheet.decisions.length()
    for reading in sheet.scan.readings {
      if sheet.decisions.get(reading.index) is Some(decision) {
        match decision.action {
          Choose(_) => answered += 1
          MarkBlank => blank += 1
          Reject => invalid += 1
        }
        continue
      }
      match reading.finding {
        Accepted => answered += 1
        Blank => blank += 1
        _ => pending += 1
      }
    }
  }
  {
    sheets: self.sheets.length(),
    answered,
    blank,
    invalid,
    pending,
    manually_reviewed,
  }
}