///|
#derive(Debug, Eq)
pub(all) enum MarkState {
  Clear
  Possible
  Filled
}

///|
#derive(Debug, Eq)
pub(all) enum Finding {
  Accepted
  Blank
  Ambiguous
  TooMany
  PoorImage
}

///|
pub struct DetectionPolicy {
  possible : Double
  filled : Double
  minimum_paper : Double
  minimum_ring : Double
}

///|
pub fn DetectionPolicy::new(
  possible : Double,
  filled : Double,
  minimum_paper : Double,
  minimum_ring : Double,
) -> DetectionPolicy raise MarkError {
  if !(possible > 0.0 && possible < filled && filled <= 1.0) ||
    !(minimum_paper >= 0.0 && minimum_paper <= 255.0) ||
    !(minimum_ring >= 0.0 && minimum_ring <= 1.0) {
    raise Invalid("invalid recognition thresholds")
  }
  { possible, filled, minimum_paper, minimum_ring, }
}

///|
pub fn DetectionPolicy::standard() -> DetectionPolicy {
  { possible: 0.13, filled: 0.40, minimum_paper: 90.0, minimum_ring: 0.10, }
}

///|
#derive(Debug, Eq)
pub(all) struct CropBox {
  x : Int32
  y : Int32
  width : Int32
  height : Int32
}

///|
pub struct BubbleReading {
  option : Int32
  state : MarkState
  score : Double
  dark_fraction : Double
  edge_ink : Double
  paper : Double
  ring : Double
  crop : CropBox
}

///|
pub struct QuestionReading {
  index : Int32
  finding : Finding
  selected : ArrayView[Int32]
  bubbles : ArrayView[BubbleReading]
}

///|
pub struct Scan {
  template : Template
  policy : DetectionPolicy
  registration : Registration
  readings : ArrayView[QuestionReading]
  image_width : Int32
  image_height : Int32
  image_fingerprint : UInt64
  printed_serial : Int32?
  priv recognition_version : Int32
}

///|
fn image_fingerprint(image : GrayImage) -> UInt64 {
  let mut hash = 14695981039346656037UL
  for value in image.pixels {
    hash = (hash ^ value.to_uint64()) * 1099511628211UL
  }
  hash = (hash ^ image.width.to_uint64()) * 1099511628211UL
  (hash ^ image.height.to_uint64()) * 1099511628211UL
}

///|
fn bubble_crop(
  image : GrayImage,
  transform : Projection,
  center : Point,
) -> CropBox raise MarkError {
  let mut left = image.width.to_double()
  let mut right = 0.0
  let mut top = image.height.to_double()
  let mut bottom = 0.0
  for dx in [-13.0, 13.0] {
    for dy in [-13.0, 13.0] {
      guard transform.map(center.x + dx, center.y + dy) is Some(p) else {
        raise RegistrationFailed("invalid inverse image coordinates")
      }
      left = @cmp.minimum(left, p.x)
      right = @cmp.maximum(right, p.x)
      top = @cmp.minimum(top, p.y)
      bottom = @cmp.maximum(bottom, p.y)
    }
  }
  let x = clamp_int(left.floor().to_int(), 0, image.width - 1)
  let y = clamp_int(top.floor().to_int(), 0, image.height - 1)
  let x_end = clamp_int(right.ceil().to_int() + 1, x + 1, image.width)
  let y_end = clamp_int(bottom.ceil().to_int() + 1, y + 1, image.height)
  { x, y, width: x_end - x, height: y_end - y, }
}

///|
fn mark_state(
  score : Double,
  edge_ink : Double,
  policy : DetectionPolicy,
) -> MarkState {
  if score >= policy.filled {
    Filled
  } else if score >= policy.possible || edge_ink >= 0.15 {
    Possible
  } else {
    Clear
  }
}

///|
fn sample_bubble(
  image : GrayImage,
  transform : Projection,
  center : Point,
  option : Int32,
  policy : DetectionPolicy,
  legacy : Bool,
) -> BubbleReading raise MarkError {
  let top = { x: center.x, y: center.y - 13.0, }
  let bottom = { x: center.x, y: center.y + 13.0, }
  guard patch_mean(image, transform, top, 1) is Some(upper) &&
    patch_mean(image, transform, bottom, 1) is Some(lower) else {
    raise RegistrationFailed("bubble background lies outside the image")
  }
  let paper = if legacy {
    (upper + lower) / 2.0
  } else {
    let samples = [upper, lower]
    for dx in [-8.0, 8.0] {
      for dy in [-13.0, 13.0] {
        guard patch_mean(
            image,
            transform,
            { x: center.x + dx, y: center.y + dy, },
            1,
          )
          is Some(value) else {
          raise RegistrationFailed("bubble background lies outside the image")
        }
        samples.push(value)
      }
    }
    samples.sort()
    (samples[2] + samples[3]) / 2.0
  }
  let normalizer = @cmp.maximum(1.0, paper)
  let mut dark = 0.0
  let mut count = 0
  let mut strong = 0
  let mut ring = 0.0
  let mut ring_count = 0
  let mut edge_dark = 0
  let mut edge_count = 0
  for row in -10..<11 {
    for column in -10..<11 {
      let distance = row * row + column * column
      let inner_edge = !legacy && distance > 36 && distance <= 64
      if distance <= 36 || inner_edge || (distance >= 90 && distance <= 112) {
        guard projected_gray(
            image,
            transform,
            center.x + column.to_double(),
            center.y + row.to_double(),
          )
          is Some(gray) else {
          raise RegistrationFailed("bubble lies outside the image")
        }
        let shade = clamp_unit((paper - gray) / normalizer)
        if distance <= 36 {
          dark += shade
          count += 1
          if shade >= 0.24 {
            strong += 1
          }
        } else if inner_edge {
          edge_count += 1
          if shade >= 0.24 {
            edge_dark += 1
          }
        } else {
          ring += shade
          ring_count += 1
        }
      }
    }
  }
  let dark_fraction = strong.to_double() / count.to_double()
  let shade = dark / count.to_double()
  let score = shade * 0.72 + dark_fraction * 0.28
  let edge_ink = if edge_count == 0 {
    0.0
  } else {
    edge_dark.to_double() / edge_count.to_double()
  }
  let state = mark_state(score, edge_ink, policy)
  {
    option,
    state,
    score,
    dark_fraction,
    edge_ink,
    paper,
    ring: ring / ring_count.to_double(),
    crop: bubble_crop(image, transform, center),
  }
}

///|
fn classify_question(
  index : Int32,
  readings : Array[BubbleReading],
  question : Question,
  policy : DetectionPolicy,
) -> QuestionReading {
  let selected : Array[Int32] = []
  let mut ambiguous = false
  let mut poor = false
  for reading in readings {
    match reading.state {
      Filled => selected.push(reading.option)
      Possible => ambiguous = true
      Clear => ()
    }
    if reading.paper < policy.minimum_paper ||
      reading.ring < policy.minimum_ring {
      poor = true
    }
  }
  let finding = if poor {
    PoorImage
  } else if selected.length() > question.max_marks {
    TooMany
  } else if ambiguous {
    Ambiguous
  } else if selected.is_empty() {
    Blank
  } else {
    Accepted
  }
  { index, finding, selected: selected[:], bubbles: readings[:], }
}

///|
pub fn scan(
  image : GrayImage,
  template : Template,
  policy~ : DetectionPolicy = DetectionPolicy::standard(),
) -> Scan raise MarkError {
  let registration = register(image, template)
  scan_registered(image, template, policy, registration, 3)
}

///|
pub fn scan_corners(
  image : GrayImage,
  template : Template,
  centers : Array[Point],
  policy~ : DetectionPolicy = DetectionPolicy::standard(),
) -> Scan raise MarkError {
  let registration = register_corners(image, template, centers)
  scan_registered(image, template, policy, registration, 3)
}

///|
fn scan_registered(
  image : GrayImage,
  template : Template,
  policy : DetectionPolicy,
  registration : Registration,
  recognition_version : Int32,
) -> Scan raise MarkError {
  let readings : Array[QuestionReading] = []
  for index in 0.. Bool {
  match self {
    Accepted | Blank => false
    Ambiguous | TooMany | PoorImage => true
  }
}

///|
pub fn Scan::pending(self : Scan) -> Array[Int32] {
  let pending : Array[Int32] = []
  for question in self.readings {
    if question.finding.needs_review() {
      pending.push(question.index)
    }
  }
  pending
}

///|
pub fn Scan::crop(
  self : Scan,
  image : GrayImage,
  question : Int32,
  option : Int32,
) -> GrayImage raise MarkError {
  if question < 0 ||
    question >= self.readings.length() ||
    option < 0 ||
    option >= self.readings[question].bubbles.length() {
    raise Invalid("requested evidence does not exist")
  }
  if image.width != self.image_width ||
    image.height != self.image_height ||
    image_fingerprint(image) != self.image_fingerprint {
    raise Invalid("evidence image differs from the scanned image")
  }
  let box = self.readings[question].bubbles[option].crop
  image.crop(box.x, box.y, box.width, box.height)
}