// Pure MoonBit port of stb_image_write v1.19 PNG writer:
// CRC-32, the five PNG scanline filters, IHDR/IDAT/IEND chunking.

///|
fn stbiw_crc32_byte(crc : UInt, b : Int) -> UInt {
  let mut c = crc ^ (b & 0xFF).reinterpret_as_uint()
  for _i = 0; _i < 8; _i = _i + 1 {
    c = if (c & (1 : UInt)) != (0 : UInt) {
      (c >> 1) ^ (0xEDB88320 : UInt)
    } else {
      c >> 1
    }
  }
  c
}

///|
/// CRC-32 of `tag` followed by `payload`, matching `stbiw__crc32`.
fn stbiw_crc32_tagged(tag : String, payload : Bytes) -> UInt {
  let mut crc : UInt = 0xFFFFFFFF
  for i = 0; i < tag.length(); i = i + 1 {
    crc = stbiw_crc32_byte(crc, tag[i].to_int())
  }
  for i = 0; i < payload.length(); i = i + 1 {
    crc = stbiw_crc32_byte(crc, payload[i].to_int())
  }
  crc ^ (0xFFFFFFFF : UInt)
}

///|
/// Emit one PNG chunk: length (big-endian), tag, payload, CRC.
fn stbiw_png_write_chunk(w : StbiwWriter, tag : String, payload : Bytes) -> Unit {
  w.write_u32be_u(payload.length().reinterpret_as_uint())
  w.write_ascii(tag)
  w.write_bytes(payload)
  w.write_u32be_u(stbiw_crc32_tagged(tag, payload))
}

///|
/// PNG Paeth predictor (`stbiw__paeth`).
fn stbiw_paeth(a : Int, b : Int, c : Int) -> Int {
  let p = a + b - c
  let pa = (p - a).abs()
  let pb = (p - b).abs()
  let pc = (p - c).abs()
  if pa <= pb && pa <= pc {
    return a
  }
  if pb <= pc {
    return b
  }
  c
}

///|
/// Build one filtered PNG scanline (`stbiw__encode_png_line`).
///
/// `filter_type` is 0..4 as in the spec; because the first scanline has no
/// predecessor row the upstream code remaps it through `firstmap`.
/// Results are stored two's-complement in `line_buffer` exactly as the C code
/// stores them into a `signed char` array.
fn stbiw_png_encode_line(
  pixels : Bytes,
  stride_bytes : Int,
  width : Int,
  height : Int,
  y : Int,
  n : Int,
  filter_type : Int,
  flip_vertically : Bool,
  line_buffer : FixedArray[Byte],
) -> Unit {
  let firstmap : FixedArray[Int] = [0, 1, 0, 5, 6]
  let mapping : FixedArray[Int] = [0, 1, 2, 3, 4]
  let ty = if y != 0 { mapping[filter_type] } else { firstmap[filter_type] }
  let z = stride_bytes * (if flip_vertically { height - 1 - y } else { y })
  let ss = if flip_vertically { -stride_bytes } else { stride_bytes }
  let row_bytes = width * n
  if ty == 0 {
    for i = 0; i < row_bytes; i = i + 1 {
      line_buffer[i] = pixels[z + i]
    }
    return
  }
  for i = 0; i < n; i = i + 1 {
    let cur = pixels[z + i].to_int()
    // The first scanline has no predecessor row; only types 2/3/4 read it.
    let pred = if ty == 2 {
      pixels[z + i - ss].to_int()
    } else if ty == 3 {
      pixels[z + i - ss].to_int() >> 1
    } else if ty == 4 {
      stbiw_paeth(0, pixels[z + i - ss].to_int(), 0)
    } else {
      0
    }
    line_buffer[i] = ((cur - pred) & 0xFF).to_byte()
  }
  if ty == 1 {
    for i = n; i < row_bytes; i = i + 1 {
      let pred = pixels[z + i - n].to_int()
      line_buffer[i] = ((pixels[z + i].to_int() - pred) & 0xFF).to_byte()
    }
  } else if ty == 2 {
    for i = n; i < row_bytes; i = i + 1 {
      let pred = pixels[z + i - ss].to_int()
      line_buffer[i] = ((pixels[z + i].to_int() - pred) & 0xFF).to_byte()
    }
  } else if ty == 3 {
    for i = n; i < row_bytes; i = i + 1 {
      let pred = (pixels[z + i - n].to_int() + pixels[z + i - ss].to_int()) >> 1
      line_buffer[i] = ((pixels[z + i].to_int() - pred) & 0xFF).to_byte()
    }
  } else if ty == 4 {
    for i = n; i < row_bytes; i = i + 1 {
      let pred = stbiw_paeth(
        pixels[z + i - n].to_int(),
        pixels[z + i - ss].to_int(),
        pixels[z + i - ss - n].to_int(),
      )
      line_buffer[i] = ((pixels[z + i].to_int() - pred) & 0xFF).to_byte()
    }
  } else if ty == 5 {
    for i = n; i < row_bytes; i = i + 1 {
      let pred = pixels[z + i - n].to_int() >> 1
      line_buffer[i] = ((pixels[z + i].to_int() - pred) & 0xFF).to_byte()
    }
  } else {
    for i = n; i < row_bytes; i = i + 1 {
      let pred = stbiw_paeth(pixels[z + i - n].to_int(), 0, 0)
      line_buffer[i] = ((pixels[z + i].to_int() - pred) & 0xFF).to_byte()
    }
  }
}

///|
/// Encode 8-bit pixels (1/2/3/4 channels) as a PNG file in memory.
///
/// `stride_in_bytes` is 0 (tightly packed) or the row pitch. `options`
/// controls vertical flip, compression level and the forced filter.
pub fn stbi_write_png_to_memory(
  width : Int,
  height : Int,
  comp : Int,
  data : Bytes,
  stride_in_bytes? : Int = 0,
  options? : StbiwOptions,
) -> Bytes? {
  let opts = match options {
    Some(o) => o
    None => StbiwOptions::default()
  }
  let stride = match stbiw_resolve_byte_stride(
    width,
    height,
    comp,
    stride_in_bytes,
    data.length(),
  ) {
    Some(s) => s
    None => return None
  }
  let ctype : FixedArray[Int] = [-1, 0, 4, 2, 6]
  let mut force_filter = opts.force_png_filter
  if force_filter >= 5 {
    force_filter = -1
  }
  let row_bytes = width * comp
  let filt : FixedArray[Byte] = FixedArray::make((row_bytes + 1) * height, (0 : Byte))
  let line_buffer : FixedArray[Byte] = FixedArray::make(row_bytes, (0 : Byte))
  for j = 0; j < height; j = j + 1 {
    let mut filter_type = 0
    if force_filter > -1 {
      filter_type = force_filter
      stbiw_png_encode_line(
        data,
        stride,
        width,
        height,
        j,
        comp,
        force_filter,
        opts.flip_vertically,
        line_buffer,
      )
    } else {
      let mut best_filter = 0
      let mut best_filter_val = 0x7FFFFFFF
      for ft = 0; ft < 5; ft = ft + 1 {
        stbiw_png_encode_line(
          data,
          stride,
          width,
          height,
          j,
          comp,
          ft,
          opts.flip_vertically,
          line_buffer,
        )
        let mut est = 0
        for i = 0; i < row_bytes; i = i + 1 {
          let v = line_buffer[i].to_int()
          est += if v >= 128 { 256 - v } else { v }
        }
        if est < best_filter_val {
          best_filter_val = est
          best_filter = ft
        }
      }
      if filter_type != best_filter {
        stbiw_png_encode_line(
          data,
          stride,
          width,
          height,
          j,
          comp,
          best_filter,
          opts.flip_vertically,
          line_buffer,
        )
        filter_type = best_filter
      }
    }
    filt[j * (row_bytes + 1)] = filter_type.to_byte()
    for i = 0; i < row_bytes; i = i + 1 {
      filt[j * (row_bytes + 1) + 1 + i] = line_buffer[i]
    }
  }
  let zlib = match stbi_zlib_compress(
    Bytes::from_array(filt[:]),
    quality=opts.png_compression_level,
  ) {
    Some(z) => z
    None => return None
  }
  let w = StbiwWriter::new(capacity=8 + 25 + 12 + zlib.length() + 12)
  w.write_u8(137)
  w.write_u8(80)
  w.write_u8(78)
  w.write_u8(71)
  w.write_u8(13)
  w.write_u8(10)
  w.write_u8(26)
  w.write_u8(10)
  let ihdr = StbiwWriter::new(capacity=13)
  ihdr.write_u32be_u(width.reinterpret_as_uint())
  ihdr.write_u32be_u(height.reinterpret_as_uint())
  ihdr.write_u8(8)
  ihdr.write_u8(ctype[comp])
  ihdr.write_u8(0)
  ihdr.write_u8(0)
  ihdr.write_u8(0)
  stbiw_png_write_chunk(w, "IHDR", ihdr.to_bytes())
  stbiw_png_write_chunk(w, "IDAT", zlib)
  stbiw_png_write_chunk(w, "IEND", Bytes::new(0))
  Some(w.to_bytes())
}