///|
/// # APNG 编解码 APNG Codec
///
/// APNG 动画 PNG 编解码实现
/// APNG 动画编解码 Animated PNG encoding/decoding
// 纯 MoonBit APNG 编解码(全目标可用:native/wasm/js)
// APNG 规范: https://wiki.mozilla.org/APNG_Specification
// APNG 是 PNG 的扩展,新增 acTL/fcTL/fdAT chunk
// 仅支持全尺寸帧(x_offset=0, y_offset=0, frame_w=width, frame_h=height)

///|
/// 从 4 字节构造 chunk type 字符串
fn apng_chunk_type(data : Bytes, offset : Int32) -> String {
  let buf : Array[Byte] = [
    data[offset],
    data[offset + 1],
    data[offset + 2],
    data[offset + 3],
  ]
  @encoding/utf8.decode(Bytes::from_array(buf)) catch {
    _ => "????"
  }
}

///|
/// PNG chunk 信息
priv struct PngChunk {
  chunk_type : String
  data_offset : Int32
  data_size : Int32
}

///|
/// 解析所有 PNG chunk
fn apng_parse_chunks(data : Bytes) -> Array[PngChunk] raise @types.LoadError {
  let len = data.length()
  if len < 8 {
    raise @types.LoadError::DecodeFailed("PNG/APNG 数据过短")
  }
  // 验证 PNG signature
  if !is_png_signature(data, 0) {
    raise @types.LoadError::DecodeFailed("PNG signature 错误")
  }
  let chunks : Array[PngChunk] = []
  let mut pos = 8
  while pos + 8 <= len {
    let chunk_len = read_u32_be(data, pos)
    let chunk_type = apng_chunk_type(data, pos + 4)
    pos += 8
    if chunk_len < 0 || chunk_len > len - pos - 4 {
      raise @types.LoadError::DecodeFailed("PNG chunk 数据越界")
    }
    chunks.push(PngChunk::{
      chunk_type,
      data_offset: pos,
      data_size: chunk_len,
    })
    pos += chunk_len + 4 // 跳过数据 + CRC
  }
  chunks
}

///|
/// 从 chunk 数据中提取子字节流
fn apng_extract_chunk_data(data : Bytes, chunk : PngChunk) -> Bytes {
  let out : Array[Byte] = []
  for i in 0.. Bytes {
  let out : Array[Byte] = []
  // PNG signature
  out.push(b'\x89')
  out.push(b'\x50')
  out.push(b'\x4E')
  out.push(b'\x47')
  out.push(b'\x0D')
  out.push(b'\x0A')
  out.push(b'\x1A')
  out.push(b'\x0A')
  // IHDR
  write_u32_be(out, ihdr_data.length())
  out.push(b'\x49')
  out.push(b'\x48')
  out.push(b'\x44')
  out.push(b'\x52')
  for i in 0.. @types.PngAnimation raise @types.LoadError {
  let chunks = apng_parse_chunks(data)
  // 查找 IHDR
  let mut ihdr_data : Bytes = b""
  let mut found_ihdr = false
  for i in 0.. Bytes raise @types.LoadError {
  let chunks = apng_parse_chunks(png_data)
  let idat : Array[Byte] = []
  for i in 0.. Bytes raise @types.LoadError {
  let chunks = apng_parse_chunks(png_data)
  for i in 0.. Unit {
  write_u32_be(out, chunk_data.length())
  let type_bytes = @encoding/utf8.encode(chunk_type)
  for i in 0..<4 {
    out.push(type_bytes[i])
  }
  for i in 0.. Bytes raise @types.LoadError {
  let num_frames = anim.frames.length()
  if num_frames == 0 {
    raise @types.LoadError::EncodeFailed("APNG 至少需要一帧")
  }
  let first = anim.frames[0]
  let width = first.width
  let height = first.height
  let out : Array[Byte] = []
  // PNG signature
  out.push(b'\x89')
  out.push(b'\x50')
  out.push(b'\x4E')
  out.push(b'\x47')
  out.push(b'\x0D')
  out.push(b'\x0A')
  out.push(b'\x1A')
  out.push(b'\x0A')
  // 编码第一帧为 PNG,提取 IHDR 和 IDAT
  let first_png = encode_png_pure(first)
  let ihdr_data = extract_ihdr_from_png(first_png)
  // IHDR chunk
  apng_write_chunk(out, "IHDR", ihdr_data)
  // acTL chunk: num_frames + num_plays(0=无限)
  let actl : Array[Byte] = []
  write_u32_be(actl, num_frames)
  write_u32_be(actl, 0)
  apng_write_chunk(out, "acTL", Bytes::from_array(actl))
  // 序列号计数器
  let mut seq = 0
  // 第一帧 fcTL
  let fctl1 : Array[Byte] = []
  write_u32_be(fctl1, seq) // sequence_number
  seq += 1
  write_u32_be(fctl1, width) // width
  write_u32_be(fctl1, height) // height
  write_u32_be(fctl1, 0) // x_offset
  write_u32_be(fctl1, 0) // y_offset
  let delay1 = if anim.delays.length() > 0 { anim.delays[0] } else { 0 }
  write_u16_be(fctl1, delay1) // delay_num (ms)
  write_u16_be(fctl1, 1000) // delay_den
  fctl1.push(b'\x01') // dispose_op = APNG_DISPOSE_OP_BACKGROUND
  fctl1.push(b'\x00') // blend_op = APNG_BLEND_OP_SOURCE
  apng_write_chunk(out, "fcTL", Bytes::from_array(fctl1))
  // 第一帧 IDAT
  let first_idat = extract_idat_from_png(first_png)
  apng_write_chunk(out, "IDAT", first_idat)
  // 后续帧
  for i in 1..