// Pure MoonBit port of stb_image_write v1.19 zlib / DEFLATE compressor.

///|
let stbiw_length_c : FixedArray[Int] = [
  3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83,
  99, 115, 131, 163, 195, 227, 258, 259,
]

///|
let stbiw_length_eb : FixedArray[Int] = [
  0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5,
  5, 0,
]

///|
let stbiw_dist_c : FixedArray[Int] = [
  1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769,
  1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 32768,
]

///|
let stbiw_dist_eb : FixedArray[Int] = [
  0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
  12, 12, 13, 13,
]

///|
fn stbiw_zlib_bitrev(code_in : Int, codebits : Int) -> Int {
  let mut code = code_in
  let mut res = 0
  for _i = 0; _i < codebits; _i = _i + 1 {
    res = (res << 1) | (code & 1)
    code = code >> 1
  }
  res
}

///|
fn stbiw_zlib_countm(data : Bytes, a : Int, b : Int, limit : Int) -> Int {
  let max_len = if limit < 258 { limit } else { 258 }
  let mut i = 0
  while i < max_len && data[a + i] == data[b + i] {
    i += 1
  }
  i
}

///|
fn stbiw_zhash(data : Bytes, pos : Int) -> Int {
  let mut hash = data[pos].to_int().reinterpret_as_uint() +
    (data[pos + 1].to_int().reinterpret_as_uint() << 8) +
    (data[pos + 2].to_int().reinterpret_as_uint() << 16)
  hash = hash ^ (hash << 3)
  hash = hash + (hash >> 5)
  hash = hash ^ (hash << 4)
  hash = hash + (hash >> 17)
  hash = hash ^ (hash << 25)
  hash = hash + (hash >> 6)
  (hash & (STBIW_ZHASH - 1).reinterpret_as_uint()).reinterpret_as_int()
}

///|
priv struct StbiwBitWriter {
  out : StbiwWriter
  mut bitbuf : UInt
  mut bitcount : Int
}

///|
fn StbiwBitWriter::flush(self : StbiwBitWriter) -> Unit {
  while self.bitcount >= 8 {
    self.out.write_u8((self.bitbuf & (0xFF : UInt)).reinterpret_as_int())
    self.bitbuf = self.bitbuf >> 8
    self.bitcount -= 8
  }
}

///|
fn StbiwBitWriter::add(
  self : StbiwBitWriter,
  code : Int,
  codebits : Int,
) -> Unit {
  self.bitbuf = self.bitbuf | (code.reinterpret_as_uint() << self.bitcount)
  self.bitcount += codebits
  self.flush()
}

///|
fn StbiwBitWriter::huffa(
  self : StbiwBitWriter,
  b : Int,
  c : Int,
) -> Unit {
  self.add(stbiw_zlib_bitrev(b, c), c)
}

///|
fn StbiwBitWriter::huff(self : StbiwBitWriter, n : Int) -> Unit {
  if n <= 143 {
    self.huffa(0x30 + n, 8)
  } else if n <= 255 {
    self.huffa(0x190 + n - 144, 9)
  } else if n <= 279 {
    self.huffa(n - 256, 7)
  } else {
    self.huffa(0xC0 + n - 280, 8)
  }
}

///|
fn StbiwBitWriter::huffb(self : StbiwBitWriter, n : Int) -> Unit {
  if n <= 143 {
    self.huffa(0x30 + n, 8)
  } else {
    self.huffa(0x190 + n - 144, 9)
  }
}

///|
/// Compress `data` into a zlib stream (pure MoonBit `stbi_zlib_compress`).
pub fn stbi_zlib_compress(data : Bytes, quality? : Int = 8) -> Bytes? {
  let data_len = data.length()
  let q = if quality < 5 { 5 } else { quality }
  let out = StbiwWriter::new(capacity=data_len + 64)
  let bw : StbiwBitWriter = { out, bitbuf: (0 : UInt), bitcount: 0 }

  out.write_u8(0x78) // DEFLATE 32K window
  out.write_u8(0x5E) // FLEVEL = 1

  if data_len == 0 {
    // Emit a single valid empty stored block so stbi_zlib_decode(stbi_zlib_compress(b"")) succeeds.
    out.write_u8(1)
    out.write_u16le(0)
    out.write_u16le(0xFFFF)
  } else {
    bw.add(1, 1) // BFINAL = 1
    bw.add(1, 2) // BTYPE = 1 -- fixed huffman

    let hash_table : FixedArray[Array[Int]?] = FixedArray::make(
      STBIW_ZHASH,
      None,
    )

    let mut i = 0
    while i < data_len - 3 {
      let h = stbiw_zhash(data, i)
      let mut best = 3
      let mut bestloc = -1
      let hlist = match hash_table[h] {
        Some(list) => list
        None => {
          let list : Array[Int] = []
          hash_table[h] = Some(list)
          list
        }
      }
      for j = 0; j < hlist.length(); j = j + 1 {
        let pos = hlist[j]
        if pos > i - 32768 {
          let d = stbiw_zlib_countm(data, pos, i, data_len - i)
          if d >= best {
            best = d
            bestloc = pos
          }
        }
      }
      if hlist.length() == 2 * q {
        for k = 0; k < q; k = k + 1 {
          hlist[k] = hlist[k + q]
        }
        hlist.truncate(q)
      }
      hlist.push(i)

      if bestloc >= 0 {
        let h2 = stbiw_zhash(data, i + 1)
        match hash_table[h2] {
          Some(hlist2) =>
            for j = 0; j < hlist2.length(); j = j + 1 {
              let pos = hlist2[j]
              if pos > i - 32767 {
                let e = stbiw_zlib_countm(data, pos, i + 1, data_len - i - 1)
                if e > best {
                  bestloc = -1
                  break
                }
              }
            }
          None => ()
        }
      }

      if bestloc >= 0 {
        let d = i - bestloc
        let mut lj = 0
        while best > stbiw_length_c[lj + 1] - 1 {
          lj += 1
        }
        bw.huff(lj + 257)
        if stbiw_length_eb[lj] != 0 {
          bw.add(best - stbiw_length_c[lj], stbiw_length_eb[lj])
        }
        let mut dj = 0
        while d > stbiw_dist_c[dj + 1] - 1 {
          dj += 1
        }
        bw.add(stbiw_zlib_bitrev(dj, 5), 5)
        if stbiw_dist_eb[dj] != 0 {
          bw.add(d - stbiw_dist_c[dj], stbiw_dist_eb[dj])
        }
        i += best
      } else {
        bw.huffb(data[i].to_int())
        i += 1
      }
    }

    while i < data_len {
      bw.huffb(data[i].to_int())
      i += 1
    }
    bw.huff(256) // end of block
    while bw.bitcount != 0 {
      bw.add(0, 1)
    }

    // Store uncompressed instead if compression expanded the payload.
    let stored_limit = data_len + 2 + ((data_len + 32766) / 32767) * 5
    if out.length() > stored_limit {
      out.truncate(2)
      let mut j = 0
      while j < data_len {
        let rem = data_len - j
        let blocklen = if rem > 32767 { 32767 } else { rem }
        out.write_u8(if rem == blocklen { 1 } else { 0 })
        out.write_u16le(blocklen)
        out.write_u16le(blocklen ^ 0xFFFF)
        out.write_bytes_slice(data, j, blocklen)
        j += blocklen
      }
    }
  }

  // Compute Adler-32 trailer on input.
  let mut s1 : UInt = 1
  let mut s2 : UInt = 0
  let mut blocklen = data_len % 5552
  let mut j = 0
  while j < data_len {
    for k = 0; k < blocklen; k = k + 1 {
      s1 = s1 + data[j + k].to_int().reinterpret_as_uint()
      s2 = s2 + s1
    }
    s1 = s1 % (65521 : UInt)
    s2 = s2 % (65521 : UInt)
    j += blocklen
    blocklen = 5552
  }
  out.write_u8(((s2 >> 8) & (0xFF : UInt)).reinterpret_as_int())
  out.write_u8((s2 & (0xFF : UInt)).reinterpret_as_int())
  out.write_u8(((s1 >> 8) & (0xFF : UInt)).reinterpret_as_int())
  out.write_u8((s1 & (0xFF : UInt)).reinterpret_as_int())
  Some(out.to_bytes())
}