///|
/// A mark in a synthetic software fixture. Its coordinates identify a bubble.
/// Offset and radius are measured in the same units as the SVG viewBox.
#derive(Debug, Eq)
pub(all) struct Ink {
  question : Int32
  option : Int32
  darkness : Int32
  radius : Int32
  dx : Int32
  dy : Int32
}

///|
pub fn Ink::solid(question : Int32, option : Int32) -> Ink {
  { question, option, darkness: 225, radius: 7, dx: 0, dy: 0, }
}

///|
fn paint_square(
  canvas : FixedArray[Byte],
  center : Point,
  half : Int32,
) -> Unit {
  let x0 = center.x.to_int()
  let y0 = center.y.to_int()
  for y in (y0 - half)..<(y0 + half + 1) {
    for x in (x0 - half)..<(x0 + half + 1) {
      canvas[y * PAGE_WIDTH + x] = b'\x08'
    }
  }
}

///|
fn paint_circle(
  canvas : FixedArray[Byte],
  x : Int32,
  y : Int32,
  inner : Int32,
  radius : Int32,
  gray : Int32,
) -> Unit {
  let exterior = radius * radius
  for dy in -radius..<(radius + 1) {
    for dx in -radius..<(radius + 1) {
      let distance = dx * dx + dy * dy
      if distance >= inner && distance <= exterior {
        let i = (y + dy) * PAGE_WIDTH + x + dx
        canvas[i] = @cmp.minimum(canvas[i].to_int(), gray).to_byte()
      }
    }
  }
}

///|
/// Render the machine-readable portion of a form for reproducible tests.
pub fn render_fixture(
  template : Template,
  marks : Array[Ink],
  serial~ : Int32? = None,
) -> GrayImage raise MarkError {
  let canvas = FixedArray::make(PAGE_WIDTH * PAGE_HEIGHT, b'\xff')
  for marker in template_markers() {
    paint_square(canvas, marker, MARKER_HALF)
  }
  for index in 0..<(CODE_BITS + 4) {
    if pilot_bit(template, index) {
      paint_square(canvas, point(pilot_x(index), PILOT_Y), 5)
    }
  }
  if serial is Some(value) {
    assert_serial(value)
    for index in 0..<33 {
      if serial_bit(value, index) {
        paint_square(canvas, point(serial_x(index), SERIAL_Y), 5)
      }
    }
  }
  for index in 0.. 1920 {
    raise Invalid("fixture has too many ink strokes")
  }
  for mark in marks {
    let center = template.bubble(mark.question, mark.option)
    if mark.dx < -10 ||
      mark.dx > 10 ||
      mark.dy < -10 ||
      mark.dy > 10 ||
      mark.radius < 1 ||
      mark.radius > 10 ||
      mark.darkness < 0 ||
      mark.darkness > 255 {
      raise Invalid("fixture ink does not fit the supported bounds")
    }
    paint_circle(
      canvas,
      center.x.to_int() + mark.dx,
      center.y.to_int() + mark.dy,
      0,
      mark.radius,
      255 - mark.darkness,
    )
  }
  GrayImage::new(PAGE_WIDTH, PAGE_HEIGHT, Bytes::from_array(canvas[:]))
}

///|
/// Simulate a photograph with a specified page quadrilateral, exposure drop,
/// and seeded noise. Corner order is canonical top-left through bottom-left.
pub fn simulate_capture(
  source : GrayImage,
  width : Int32,
  height : Int32,
  corners : Array[Point],
  shadow : Int32,
  noise : Int32,
  seed : UInt32,
) -> GrayImage raise MarkError {
  ignore(checked_pixels(width, height))
  if shadow < 0 || shadow > 160 || noise < 0 || noise > 60 {
    raise Invalid("capture distortion is outside its supported range")
  }
  for corner in corners {
    if !(corner.x >= 0.0 &&
      corner.x < width.to_double() &&
      corner.y >= 0.0 &&
      corner.y < height.to_double()) {
      raise Invalid("capture quadrilateral lies outside the image")
    }
  }
  let source_corners = [
    point(0, 0),
    point(source.width - 1, 0),
    point(source.width - 1, source.height - 1),
    point(0, source.height - 1),
  ]
  guard projection(corners, source_corners) is Some(transform) else {
    raise Invalid("capture quadrilateral is degenerate or not clockwise")
  }
  let warped = warp(source, transform, width, height)
  let mut state = seed
  let output = FixedArray::makei(width * height, i => {
    state = state * 1664525U + 1013904223U
    let sample = ((state >> 16) % (noise * 2 + 1).reinterpret_as_uint()).reinterpret_as_int() -
      noise
    let ramp = i % width * shadow / @cmp.maximum(width - 1, 1)
    let exposed = warped.pixels[i].to_int() * (255 - ramp) / 255
    clamp_int(exposed + sample, 0, 255).to_byte()
  })
  GrayImage::new(width, height, Bytes::from_array(output[:]))
}