///|
fn jint(value : Int32) -> Json {
  Json::number(value.to_double())
}

///|
fn jints(values : ArrayView[Int32]) -> Json {
  let items : Array[Json] = []
  for value in values {
    items.push(jint(value))
  }
  Json::array(items)
}

///|
fn jpoint(value : Point) -> Json {
  Json::object(
    Map([("x", Json::number(value.x)), ("y", Json::number(value.y))]),
  )
}

///|
fn jcrop(value : CropBox) -> Json {
  Json::object(
    Map([
      ("x", jint(value.x)),
      ("y", jint(value.y)),
      ("width", jint(value.width)),
      ("height", jint(value.height)),
    ]),
  )
}

///|
fn json_object(
  value : Json,
  label : String,
) -> Map[String, Json] raise MarkError {
  match value {
    Object(fields) => fields
    _ => raise Invalid("\{label} must be a JSON object")
  }
}

///|
fn json_array(value : Json, label : String) -> Array[Json] raise MarkError {
  match value {
    Array(entries) => entries
    _ => raise Invalid("\{label} must be a JSON array")
  }
}

///|
fn required(fields : Map[String, Json], key : String) -> Json raise MarkError {
  match fields.get(key) {
    Some(value) => value
    None => raise Invalid("missing JSON field \{key}")
  }
}

///|
fn json_string(value : Json, label : String) -> String raise MarkError {
  match value {
    String(text) => text
    _ => raise Invalid("\{label} must be a string")
  }
}

///|
fn json_number(value : Json, label : String) -> Double raise MarkError {
  match value {
    Number(number, ..) if !number.is_nan() && !number.is_inf() => number
    _ => raise Invalid("\{label} must be a finite number")
  }
}

///|
fn json_int(value : Json, label : String) -> Int32 raise MarkError {
  let number = json_number(value, label)
  if number < -2147483648.0 || number > 2147483647.0 || number != number.floor() {
    raise Invalid("\{label} must be a signed 32-bit integer")
  }
  number.to_int()
}

///|
fn json_ints(value : Json, label : String) -> Array[Int32] raise MarkError {
  let output : Array[Int32] = []
  for item in json_array(value, label) {
    output.push(json_int(item, label))
  }
  output
}

///|
pub fn parse_json(text : String) -> Json raise MarkError {
  if text.length() > 8000000 {
    raise Invalid("JSON document exceeds the input limit")
  }
  @json.parse(text[:], reject_duplicate_keys=true) catch {
    _ => raise Invalid("invalid JSON or duplicate object key")
  }
}

///|
fn assert_version(fields : Map[String, Json]) -> Unit raise MarkError {
  if json_int(required(fields, "version"), "version") != 1 {
    raise Invalid("unsupported JSON document version")
  }
}

///|
pub fn Template::json(self : Template) -> Json {
  let questions : Array[Json] = []
  for question in self.questions {
    questions.push(
      Json::object(
        Map([
          ("options", jint(question.options)),
          ("max_marks", jint(question.max_marks)),
        ]),
      ),
    )
  }
  Json::object(
    Map([
      ("version", jint(1)),
      ("title", Json::string(self.title)),
      ("questions", Json::array(questions)),
    ]),
  )
}

///|
pub fn Template::from_json(value : Json) -> Template raise MarkError {
  let fields = json_object(value, "template")
  assert_version(fields)
  let title = json_string(required(fields, "title"), "title")
  let entries = json_array(required(fields, "questions"), "questions")
  if entries.length() > 60 {
    raise Invalid("template exceeds 60 questions")
  }
  let questions : Array[Question] = []
  for entry in entries {
    let row = json_object(entry, "question")
    questions.push({
      options: json_int(required(row, "options"), "options"),
      max_marks: json_int(required(row, "max_marks"), "max_marks"),
    })
  }
  Template::new(title, questions)
}

///|
pub fn DetectionPolicy::json(self : DetectionPolicy) -> Json {
  Json::object(
    Map([
      ("possible", Json::number(self.possible)),
      ("filled", Json::number(self.filled)),
      ("minimum_paper", Json::number(self.minimum_paper)),
      ("minimum_ring", Json::number(self.minimum_ring)),
    ]),
  )
}

///|
pub fn DetectionPolicy::from_json(
  value : Json,
) -> DetectionPolicy raise MarkError {
  let fields = json_object(value, "recognition policy")
  DetectionPolicy::new(
    json_number(required(fields, "possible"), "possible"),
    json_number(required(fields, "filled"), "filled"),
    json_number(required(fields, "minimum_paper"), "minimum_paper"),
    json_number(required(fields, "minimum_ring"), "minimum_ring"),
  )
}

///|
pub fn BubbleReading::json(self : BubbleReading) -> Json {
  Json::object(
    Map([
      ("option", jint(self.option)),
      ("state", Json::string(mark_text(self.state))),
      ("score", Json::number(self.score)),
      ("dark_fraction", Json::number(self.dark_fraction)),
      ("edge_ink", Json::number(self.edge_ink)),
      ("paper", Json::number(self.paper)),
      ("ring", Json::number(self.ring)),
      ("crop", jcrop(self.crop)),
    ]),
  )
}

///|
pub fn QuestionReading::json(self : QuestionReading) -> Json {
  let bubbles : Array[Json] = []
  for bubble in self.bubbles {
    bubbles.push(bubble.json())
  }
  Json::object(
    Map([
      ("index", jint(self.index)),
      ("finding", Json::string(finding_text(self.finding))),
      ("selected", jints(self.selected)),
      ("bubbles", Json::array(bubbles)),
    ]),
  )
}

///|
pub fn Registration::json(self : Registration) -> Json {
  let corners : Array[Json] = []
  for corner in self.corners {
    corners.push(jpoint(corner))
  }
  Json::object(
    Map([
      ("corners", Json::array(corners)),
      ("orientation", jint(self.orientation)),
      ("contrast", Json::number(self.contrast)),
      ("manual", Json::boolean(self.manual)),
    ]),
  )
}

///|
pub fn Scan::json(self : Scan) -> Json {
  let results : Array[Json] = []
  for question in self.readings {
    results.push(question.json())
  }
  Json::object(
    Map([
      ("version", jint(1)),
      ("template", self.template.json()),
      ("policy", self.policy.json()),
      ("registration", self.registration.json()),
      ("image_width", jint(self.image_width)),
      ("image_height", jint(self.image_height)),
      ("image_fingerprint", Json::string(self.image_fingerprint.to_string())),
      ("printed_serial", self.printed_serial.map(jint).unwrap_or(Json::null())),
      ("readings", Json::array(results)),
      ("pending", jints(self.pending()[:])),
    ]),
  )
}

///|
pub fn Outcome::json(self : Outcome) -> Json {
  let (status, selected) = match self {
    MissingReview => ("pending", Json::null())
    Responded(answers) => ("answered", jints(answers))
    NoResponse => ("blank", Json::array([]))
    InvalidResponse => ("invalid", Json::null())
  }
  Json::object(Map([("status", Json::string(status)), ("selected", selected)]))
}

///|
pub fn ReviewAction::json(self : ReviewAction) -> Json {
  let (kind, picked) = match self {
    Choose(options) => ("choose", jints(options))
    MarkBlank => ("blank", Json::array([]))
    Reject => ("reject", Json::array([]))
  }
  Json::object(Map([("action", Json::string(kind)), ("options", picked)]))
}

///|
pub fn ReviewAction::from_json(value : Json) -> ReviewAction raise MarkError {
  let fields = json_object(value, "review action")
  let action = json_string(required(fields, "action"), "action")
  let choices = json_ints(required(fields, "options"), "options")
  match action {
    "choose" => Choose(choices[:])
    "blank" if choices.is_empty() => MarkBlank
    "reject" if choices.is_empty() => Reject
    _ => raise Invalid("invalid review action or unexpected options")
  }
}

///|
fn Decision::json(self : Decision) -> Json {
  Json::object(
    Map([("decision", self.action.json()), ("note", Json::string(self.note))]),
  )
}

///|
fn decision_or_null(value : Decision?) -> Json {
  value.map(decision => decision.json()).unwrap_or(Json::null())
}

///|
pub fn ReviewEvent::json(self : ReviewEvent) -> Json {
  Json::object(
    Map([
      ("revision", jint(self.revision)),
      ("question", jint(self.question)),
      ("previous", decision_or_null(self.previous)),
      ("current", decision_or_null(self.current)),
    ]),
  )
}

///|
pub fn Sheet::journal(self : Sheet) -> Json {
  let events : Array[Json] = []
  for event in self.history {
    events.push(event.json())
  }
  Json::object(
    Map([
      ("version", jint(1)),
      ("sheet_id", Json::string(self.id)),
      ("template", self.scan.template.json()),
      ("policy", self.scan.policy.json()),
      ("recognition_version", jint(self.scan.recognition_version)),
      (
        "image_fingerprint",
        Json::string(self.scan.image_fingerprint.to_string()),
      ),
      (
        "manual_corners",
        if self.scan.registration.manual {
          let points : Array[Json] = []
          for corner in self.scan.registration.corners {
            points.push(jpoint(corner))
          }
          Json::array(points)
        } else {
          Json::null()
        },
      ),
      ("events", Json::array(events)),
    ]),
  )
}

///|
fn journal_version(fields : Map[String, Json]) -> Int32 raise MarkError {
  match fields.get("recognition_version") {
    None => 1
    Some(value) =>
      match json_int(value, "recognition version") {
        1 | 2 | 3 as version => version
        _ => raise Invalid("unsupported recognition version")
      }
  }
}

///|
pub fn replay_journal(scan : Scan, journal : Json) -> Sheet raise MarkError {
  let fields = json_object(journal, "review journal")
  assert_version(fields)
  if required(fields, "image_fingerprint") !=
    Json::string(scan.image_fingerprint.to_string()) ||
    required(fields, "template") != scan.template.json() ||
    required(fields, "policy") != scan.policy.json() ||
    journal_version(fields) != scan.recognition_version {
    raise Invalid("journal image, template or recognition policy differs")
  }
  let sheet = Sheet::new(
    json_string(required(fields, "sheet_id"), "sheet_id"),
    scan,
  )
  if fields.get("manual_corners").unwrap_or(Json::null()) !=
    required(json_object(sheet.journal(), "current journal"), "manual_corners") {
    raise Invalid("journal manual registration differs from the scan")
  }
  let entries = json_array(required(fields, "events"), "events")
  if entries.length() > 10000 {
    raise Invalid("review journal exceeds the revision limit")
  }
  for entry in entries {
    let event = json_object(entry, "review event")
    let revision = sheet.revision()
    let index = json_int(required(event, "question"), "question")
    if json_int(required(event, "revision"), "revision") != revision + 1 ||
      required(event, "previous") != decision_or_null(sheet.decision(index)) {
      raise Invalid("review journal has inconsistent revision history")
    }
    match required(event, "current") {
      Null => sheet.reset(index, revision)
      current => {
        let payload = json_object(current, "decision")
        let action = ReviewAction::from_json(required(payload, "decision"))
        let note = json_string(required(payload, "note"), "note")
        sheet.review(index, action, note, revision)
        if decision_or_null(sheet.decision(index)) != current {
          raise Invalid("review journal decision is not canonical")
        }
      }
    }
  }
  sheet
}

///|
pub fn corners_from_json(data : Json) -> Array[Point] raise MarkError {
  let entries = json_array(data, "corner centers")
  if entries.length() != 4 {
    raise Invalid("provide four corner centers in template order")
  }
  let corners : Array[Point] = []
  for entry in entries {
    let fields = json_object(entry, "corner center")
    corners.push({
      x: json_number(required(fields, "x"), "corner center x"),
      y: json_number(required(fields, "y"), "corner center y"),
    })
  }
  corners
}

///|
pub fn resume_sheet(
  image : GrayImage,
  template : Template,
  journal : Json,
) -> Sheet raise MarkError {
  let fields = json_object(journal, "review journal")
  assert_version(fields)
  if required(fields, "template") != template.json() ||
    required(fields, "image_fingerprint") !=
    Json::string(image_fingerprint(image).to_string()) {
    raise Invalid("journal image or template differs")
  }
  let policy = DetectionPolicy::from_json(required(fields, "policy"))
  let version = journal_version(fields)
  let registration = match fields.get("manual_corners") {
    None | Some(Null) => register_version(image, template, version)
    Some(corners) =>
      register_corners_version(
        image,
        template,
        corners_from_json(corners),
        version == 1,
      )
  }
  let captured = scan_registered(image, template, policy, registration, version)
  replay_journal(captured, journal)
}

///|
pub fn Sheet::json(self : Sheet) -> Json raise MarkError {
  let answers : Array[Json] = []
  for reading in self.scan.readings {
    let index = reading.index
    answers.push(
      Json::object(
        Map([
          ("question", jint(index)),
          ("outcome", self.outcome(index).json()),
          ("manual", decision_or_null(self.decision(index))),
        ]),
      ),
    )
  }
  Json::object(
    Map([
      ("scan", self.scan.json()),
      ("journal", self.journal()),
      ("answers", Json::array(answers)),
      ("pending", jints(self.pending()[:])),
    ]),
  )
}

///|
pub fn BatchSummary::json(self : BatchSummary) -> Json {
  Json::object(
    Map([
      ("sheets", jint(self.sheets)),
      ("answered", jint(self.answered)),
      ("blank", jint(self.blank)),
      ("invalid", jint(self.invalid)),
      ("pending", jint(self.pending)),
      ("manually_reviewed", jint(self.manually_reviewed)),
    ]),
  )
}