///|
/// Per-question distribution preserves original machine findings after
/// a reviewer corrects an answer.
pub struct QuestionAudit {
  index : Int32
  sheets : Int32
  machine : Map[String, Int32]
  final_states : Map[String, Int32]
  manual : Int32
  changed : Int32
  option_counts : ArrayView[Int32]
}

///|
fn initial_outcome(reading : QuestionReading) -> Outcome {
  match reading.finding {
    Accepted => Responded(reading.selected)
    Blank => NoResponse
    _ => MissingReview
  }
}

///|
fn increase(map : Map[String, Int32], key : String) -> Unit {
  map[key] = map.get(key).unwrap_or(0) + 1
}

///|
pub fn Batch::audit(self : Batch) -> Array[QuestionAudit] raise MarkError {
  let output : Array[QuestionAudit] = []
  for index in 0.. increase(final_states, "pending")
        NoResponse => increase(final_states, "blank")
        InvalidResponse => increase(final_states, "invalid")
        Responded(selected) => {
          increase(final_states, "answered")
          for option in selected {
            options[option] += 1
          }
        }
      }
    }
    output.push({
      index,
      sheets: self.sheets.length(),
      machine,
      final_states,
      manual,
      changed,
      option_counts: options[:],
    })
  }
  output
}

///|
fn count_object(counts : Map[String, Int32]) -> Json {
  let object : Map[String, Json] = Map([])
  for key, count in counts {
    object[key] = jint(count)
  }
  Json::object(object)
}

///|
pub fn QuestionAudit::json(self : QuestionAudit) -> Json {
  Json::object(
    Map([
      ("question", jint(self.index)),
      ("sheets", jint(self.sheets)),
      ("machine", count_object(self.machine)),
      ("final", count_object(self.final_states)),
      ("manual", jint(self.manual)),
      ("changed", jint(self.changed)),
      ("option_counts", jints(self.option_counts)),
    ]),
  )
}

///|
pub fn Batch::audit_json(self : Batch) -> Json raise MarkError {
  let questions = self.audit().map(question => question.json())
  Json::object(
    Map([
      ("version", jint(1)),
      ("template", self.template.json()),
      ("summary", self.summary().json()),
      ("questions", Json::array(questions)),
    ]),
  )
}

///|
pub fn Batch::audit_csv(self : Batch) -> String raise MarkError {
  let output = StringBuilder()
  output.write_string(
    "question,sheets,machine_accepted,machine_blank,machine_ambiguous,machine_too_many,machine_poor_image,pending,answered,blank,invalid,manual,changed,A,B,C,D,E,F,G,H\r\n",
  )
  for item in self.audit() {
    output.write_string("\{item.index + 1},\{item.sheets}")
    for kind in ["accepted", "blank", "ambiguous", "too_many", "poor_image"] {
      output.write_string(",\{item.machine[kind]}")
    }
    for kind in ["pending", "answered", "blank", "invalid"] {
      output.write_string(",\{item.final_states[kind]}")
    }
    output.write_string(",\{item.manual},\{item.changed}")
    for option in 0..<8 {
      output.write_char(',')
      if option < item.option_counts.length() {
        output.write_string(item.option_counts[option].to_string())
      }
    }
    output.write_string("\r\n")
  }
  output.to_string()
}