///|
pub(all) suberror OraError {
  InvalidDocument(String)
  Unsupported(String)
}

///|
pub struct Image {
  width : Int32
  height : Int32
  priv pixels : Array[Byte]
  priv bits : Int32
  priv vector_source : Bytes?
}

///|
pub fn Image::new(
  width : Int32,
  height : Int32,
  pixels : Array[Byte],
) -> Image raise OraError {
  check_image_size(width, height)
  if pixels.length() != width * height * 4 {
    raise InvalidDocument("RGBA length mismatch")
  }
  { width, height, pixels: pixels.copy(), bits: 8, vector_source: None, }
}

///|
fn check_image_size(width : Int32, height : Int32) -> Unit raise OraError {
  if width <= 0 ||
    height <= 0 ||
    width > 16384 ||
    height > 16384 ||
    width.to_int64() * height.to_int64() > 16777216 {
    raise InvalidDocument("Image dimensions exceed limits")
  }
}

///|
/// Construct straight RGBA from unsigned 16-bit channel values.
pub fn Image::new_rgba16(
  width : Int32,
  height : Int32,
  samples : Array[Int32],
) -> Image raise OraError {
  check_image_size(width, height)
  if samples.length() != width * height * 4 {
    raise InvalidDocument("RGBA length mismatch")
  }
  if samples.any(v => v < 0 || v > 65535) {
    raise InvalidDocument("16-bit RGBA samples must be in 0..65535")
  }
  let image = blank_image(width, height, 16)
  for i, value in samples {
    image.put_sample(i, value)
  }
  image
}

///|
fn blank_image(width : Int32, height : Int32, bits : Int32) -> Image {
  {
    width,
    height,
    bits,
    pixels: Array::make(width * height * (bits / 2), 0),
    vector_source: None,
  }
}

///|
pub fn Image::bit_depth(self : Image) -> Int32 {
  self.bits
}

///|
fn Image::sample(self : Image, i : Int32) -> Int32 {
  if self.bits == 8 {
    self.pixels[i].to_int()
  } else {
    self.pixels[2 * i].to_int() * 256 + self.pixels[2 * i + 1].to_int()
  }
}

///|
fn Image::put_sample(self : Image, i : Int32, value : Int32) -> Unit {
  if self.bits == 8 {
    self.pixels[i] = value.to_byte()
  } else {
    self.pixels[2 * i] = (value / 256).to_byte()
    self.pixels[2 * i + 1] = (value % 256).to_byte()
  }
}

///|
/// Copy full-precision samples, promoting 8-bit values by multiplication by 257.
pub fn Image::pixels_rgba16(self : Image) -> Array[Int32] {
  let scale = if self.bits == 8 { 257 } else { 1 }
  Array::makei(self.width * self.height * 4, i => self.sample(i) * scale)
}

///|
fn Image::as_preview(self : Image) -> Image {
  if self.bits == 8 {
    self
  } else {
    { ..self, pixels: self.pixels(), bits: 8, vector_source: None, }
  }
}

///|
pub fn Image::width(self : Image) -> Int32 {
  self.width
}

///|
pub fn Image::height(self : Image) -> Int32 {
  self.height
}

///|
pub fn Image::pixels(self : Image) -> Array[Byte] {
  if self.bits == 8 {
    self.pixels.copy()
  } else {
    Array::makei(self.width * self.height * 4, i => {
      ((self.sample(i) + 128) / 257).to_byte()
    })
  }
}

///|
pub(all) enum Isolation {
  Auto
  Isolate
}

///|
pub struct Properties {
  name : String
  x : Int32
  y : Int32
  visible : Bool
  opacity : Double
  composite_op : String
  priv extra : Array[(String, String)]
}

///|
pub fn Properties::new(
  name : String,
  x~ : Int32 = 0,
  y~ : Int32 = 0,
  visible~ : Bool = true,
  opacity~ : Double = 1.0,
  composite_op~ : String = "svg:src-over",
) -> Properties raise OraError {
  if opacity.is_nan() || opacity < 0.0 || opacity > 1.0 {
    raise InvalidDocument("Opacity must be between zero and one")
  }
  if x < -1000000 || x > 1000000 || y < -1000000 || y > 1000000 {
    raise InvalidDocument("Offset exceeds limits")
  }
  { name, x, y, visible, opacity, composite_op, extra: [], }
}

///|
pub(all) enum Node {
  Layer(Properties, Image)
  Group(Properties, Isolation, Array[Node])
}

///|
pub struct Document {
  width : Int32
  height : Int32
  name : String
  priv children : Array[Node]
  priv root_properties : Properties?
  priv image_attributes : Array[(String, String)]
  priv resources : Array[(String, Bytes)]
}

///|
pub fn Document::new(
  width : Int32,
  height : Int32,
  children : Array[Node],
  name~ : String = "Untitled",
) -> Document raise OraError {
  if width <= 0 ||
    height <= 0 ||
    width > 16384 ||
    height > 16384 ||
    width.to_int64() * height.to_int64() > 16777216 {
    raise InvalidDocument("Canvas dimensions exceed limits")
  }
  validate_nodes(children, 0, Ref(0L), Ref(0))
  {
    width,
    height,
    name,
    children: children.map(copy_node),
    root_properties: None,
    image_attributes: [],
    resources: [],
  }
}

///|
pub fn Document::width(self : Document) -> Int32 {
  self.width
}

///|
pub fn Document::height(self : Document) -> Int32 {
  self.height
}

///|
pub fn Document::name(self : Document) -> String {
  self.name
}

///|
pub fn Document::children(self : Document) -> Array[Node] {
  self.children.map(copy_node)
}

///|
/// A readable diagnostic preserving the affected resource or property.
pub fn OraError::message(self : OraError) -> String {
  match self {
    InvalidDocument(s) => "Invalid OpenRaster document: " + s
    Unsupported(s) => "Unsupported OpenRaster feature: " + s
  }
}

///|
fn validate_nodes(
  nodes : Array[Node],
  depth : Int32,
  bytes : Ref[Int64],
  count : Ref[Int32],
) -> Unit raise OraError {
  if depth > 128 {
    raise InvalidDocument("Layer tree exceeds depth limit")
  }
  for node in nodes {
    count.val = count.val + 1
    if count.val > 4096 {
      raise InvalidDocument("Layer count exceeds limit")
    }
    match node {
      Layer(_, image) => {
        bytes.val = bytes.val + image.storage_bytes()
        if bytes.val > 134217728L {
          raise InvalidDocument("Decoded layer pixels exceed 128 MiB budget")
        }
      }
      Group(_, _, children) => validate_nodes(children, depth + 1, bytes, count)
    }
  }
}

///|
/// Precision of the composite, including the depth of hidden layers.
pub fn Document::bit_depth(self : Document) -> Int32 {
  fn wide(nodes : Array[Node]) -> Bool {
    nodes.any(node => {
      match node {
        Layer(_, image) => image.bits == 16
        Group(_, _, children) => wide(children)
      }
    })
  }
  if wide(self.children) {
    16
  } else {
    8
  }
}

///|
/// The original SVG bytes, if this image is backed by a vector layer.
pub fn Image::svg_source(self : Image) -> Bytes? {
  self.vector_source
}

///|
/// Logical bytes retained by the image and its optional SVG source.
pub fn Image::storage_bytes(self : Image) -> Int64 {
  self.pixels.length().to_int64() +
  (match self.vector_source {
    Some(data) => data.length().to_int64()
    None => 0L
  })
}