///|
/// SHA-512 initial hash values (FIPS 180-4).
let sha512_h0 : Array[UInt64] = [
  0x6a09e667f3bcc908UL, 0xbb67ae8584caa73bUL, 0x3c6ef372fe94f82bUL, 0xa54ff53a5f1d36f1UL,
  0x510e527fade682d1UL, 0x9b05688c2b3e6c1fUL, 0x1f83d9abfb41bd6bUL, 0x5be0cd19137e2179UL,
]

///|
/// SHA-512 round constants.
let sha512_k : Array[UInt64] = [
  0x428a2f98d728ae22UL, 0x7137449123ef65cdUL, 0xb5c0fbcfec4d3b2fUL, 0xe9b5dba58189dbbcUL,
  0x3956c25bf348b538UL, 0x59f111f1b605d019UL, 0x923f82a4af194f9bUL, 0xab1c5ed5da6d8118UL,
  0xd807aa98a3030242UL, 0x12835b0145706fbeUL, 0x243185be4ee4b28cUL, 0x550c7dc3d5ffb4e2UL,
  0x72be5d74f27b896fUL, 0x80deb1fe3b1696b1UL, 0x9bdc06a725c71235UL, 0xc19bf174cf692694UL,
  0xe49b69c19ef14ad2UL, 0xefbe4786384f25e3UL, 0x0fc19dc68b8cd5b5UL, 0x240ca1cc77ac9c65UL,
  0x2de92c6f592b0275UL, 0x4a7484aa6ea6e483UL, 0x5cb0a9dcbd41fbd4UL, 0x76f988da831153b5UL,
  0x983e5152ee66dfabUL, 0xa831c66d2db43210UL, 0xb00327c898fb213fUL, 0xbf597fc7beef0ee4UL,
  0xc6e00bf33da88fc2UL, 0xd5a79147930aa725UL, 0x06ca6351e003826fUL, 0x142929670a0e6e70UL,
  0x27b70a8546d22ffcUL, 0x2e1b21385c26c926UL, 0x4d2c6dfc5ac42aedUL, 0x53380d139d95b3dfUL,
  0x650a73548baf63deUL, 0x766a0abb3c77b2a8UL, 0x81c2c92e47edaee6UL, 0x92722c851482353bUL,
  0xa2bfe8a14cf10364UL, 0xa81a664bbc423001UL, 0xc24b8b70d0f89791UL, 0xc76c51a30654be30UL,
  0xd192e819d6ef5218UL, 0xd69906245565a910UL, 0xf40e35855771202aUL, 0x106aa07032bbd1b8UL,
  0x19a4c116b8d2d0c8UL, 0x1e376c085141ab53UL, 0x2748774cdf8eeb99UL, 0x34b0bcb5e19b48a8UL,
  0x391c0cb3c5c95a63UL, 0x4ed8aa4ae3418acbUL, 0x5b9cca4f7763e373UL, 0x682e6ff3d6b2b8a3UL,
  0x748f82ee5defb2fcUL, 0x78a5636f43172f60UL, 0x84c87814a1f0ab72UL, 0x8cc702081a6439ecUL,
  0x90befffa23631e28UL, 0xa4506cebde82bde9UL, 0xbef9a3f7b2c67915UL, 0xc67178f2e372532bUL,
  0xca273eceea26619cUL, 0xd186b8c721c0c207UL, 0xeada7dd6cde0eb1eUL, 0xf57d4f7fee6ed178UL,
  0x06f067aa72176fbaUL, 0x0a637dc5a2c898a6UL, 0x113f9804bef90daeUL, 0x1b710b35131c471bUL,
  0x28db77f523047d84UL, 0x32caab7b40c72493UL, 0x3c9ebe0a15c9bebcUL, 0x431d67c49c100d4cUL,
  0x4cc5d4becb3e42b6UL, 0x597f299cfc657e2aUL, 0x5fcb6fab3ad6faecUL, 0x6c44198c4a475817UL,
]

///|
/// SHA-512 state.
pub(all) struct Sha512 {
  mut h : Array[UInt64]
  mut buffer : Array[Byte]
  mut total_len : UInt64
}

///|
/// Create a new SHA-512 hasher.
pub fn Sha512::new() -> Sha512 {
  { h: sha512_h0.copy(), buffer: [], total_len: 0UL }
}

///|
/// Feed data into the hasher.
pub fn Sha512::write(self : Sha512, data : Bytes) -> Unit {
  let mut i = 0
  while i < data.length() {
    self.buffer.push(data[i])
    if self.buffer.length() == 128 {
      self.process_block(self.buffer)
      self.buffer = []
    }
    i += 1
  }
  self.total_len += data.length().to_uint64()
}

///|
fn rotr64(x : UInt64, n : Int) -> UInt64 {
  (x >> n) | (x << (64 - n))
}

///|
fn Sha512::process_block(self : Sha512, block : Array[Byte]) -> Unit {
  let w : Array[UInt64] = Array::make(80, 0UL)
  let mut i = 0
  while i < 16 {
    w[i] = (block[i * 8].to_uint64() << 56) |
      (block[i * 8 + 1].to_uint64() << 48) |
      (block[i * 8 + 2].to_uint64() << 40) |
      (block[i * 8 + 3].to_uint64() << 32) |
      (block[i * 8 + 4].to_uint64() << 24) |
      (block[i * 8 + 5].to_uint64() << 16) |
      (block[i * 8 + 6].to_uint64() << 8) |
      block[i * 8 + 7].to_uint64()
    i += 1
  }
  while i < 80 {
    let s0 = rotr64(w[i - 15], 1) ^ rotr64(w[i - 15], 8) ^ (w[i - 15] >> 7)
    let s1 = rotr64(w[i - 2], 19) ^ rotr64(w[i - 2], 61) ^ (w[i - 2] >> 6)
    w[i] = w[i - 16] + s0 + w[i - 7] + s1
    i += 1
  }
  let mut a = self.h[0]
  let mut b = self.h[1]
  let mut c = self.h[2]
  let mut d = self.h[3]
  let mut e = self.h[4]
  let mut f = self.h[5]
  let mut g = self.h[6]
  let mut h = self.h[7]
  i = 0
  while i < 80 {
    let s1 = rotr64(e, 14) ^ rotr64(e, 18) ^ rotr64(e, 41)
    let ch = (e & f) ^ (e.lnot() & g)
    let temp1 = h + s1 + ch + sha512_k[i] + w[i]
    let s0 = rotr64(a, 28) ^ rotr64(a, 34) ^ rotr64(a, 39)
    let maj = (a & b) ^ (a & c) ^ (b & c)
    let temp2 = s0 + maj
    h = g
    g = f
    f = e
    e = d + temp1
    d = c
    c = b
    b = a
    a = temp1 + temp2
    i += 1
  }
  self.h[0] += a
  self.h[1] += b
  self.h[2] += c
  self.h[3] += d
  self.h[4] += e
  self.h[5] += f
  self.h[6] += g
  self.h[7] += h
}

///|
/// Finalize and return the 64-byte digest.
pub fn Sha512::finalize(self : Sha512) -> Bytes {
  let bit_len = self.total_len * 8UL
  self.buffer.push(b'\x80')
  while self.buffer.length() % 128 != 112 {
    self.buffer.push(b'\x00')
  }
  // Append 128-bit big-endian length (high 64 bits are 0 for our use case)
  for _ in 0..<8 {
    self.buffer.push(b'\x00')
  }
  for i in [0, 1, 2, 3, 4, 5, 6, 7] {
    let shift = (7 - i) * 8
    self.buffer.push(((bit_len >> shift) & 0xFFUL).to_byte())
  }
  let mut start = 0
  while start < self.buffer.length() {
    let block : Array[Byte] = []
    for j in 0..<128 {
      block.push(self.buffer[start + j])
    }
    self.process_block(block)
    start += 128
  }
  let result : Array[Byte] = []
  for i in 0..<8 {
    let val = self.h[i]
    for j in [0, 1, 2, 3, 4, 5, 6, 7] {
      let shift = (7 - j) * 8
      result.push(((val >> shift) & 0xFFUL).to_byte())
    }
  }
  Bytes::from_array(result)
}

///|
/// One-shot SHA-512 hash.
pub fn sha512(data : Bytes) -> Bytes {
  let h = Sha512::new()
  h.write(data)
  h.finalize()
}

///|
/// SHA-384: SHA-512 with different IV and truncated to 48 bytes.
let sha384_h0 : Array[UInt64] = [
  0xcbbb9d5dc1059ed8UL, 0x629a292a367cd507UL, 0x9159015a3070dd17UL, 0x152fecd8f70e5939UL,
  0x67332667ffc00b31UL, 0x8eb44a8768581511UL, 0xdb0c2e0d64f98fa7UL, 0x47b5481dbefa4fa4UL,
]

///|
/// SHA-384 state (uses SHA-512 internally with different IV).
pub(all) struct Sha384 {
  mut inner : Sha512
}

///|
pub fn Sha384::new() -> Sha384 {
  let s = Sha512::new()
  s.h = sha384_h0.copy()
  { inner: s }
}

///|
pub fn Sha384::write(self : Sha384, data : Bytes) -> Unit {
  self.inner.write(data)
}

///|
pub fn Sha384::finalize(self : Sha384) -> Bytes {
  let full = self.inner.finalize()
  // Truncate to 48 bytes
  let result : Array[Byte] = []
  for i in 0..<48 {
    result.push(full[i])
  }
  Bytes::from_array(result)
}

///|
pub fn sha384(data : Bytes) -> Bytes {
  let h = Sha384::new()
  h.write(data)
  h.finalize()
}

///|
/// SHA-512 hex string output.
pub fn sha512_hex(data : String) -> String {
  let digest = sha512(@utf8.encode(data))
  let hex_chars : Array[Char] = [
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
  ]
  let sb : Array[Char] = []
  for i in 0..> 4) & 0xF])
    sb.push(hex_chars[b & 0xF])
  }
  String::from_array(sb)
}

///|
/// SHA-384 hex string output.
pub fn sha384_hex(data : String) -> String {
  let digest = sha384(@utf8.encode(data))
  let hex_chars : Array[Char] = [
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
  ]
  let sb : Array[Char] = []
  for i in 0..> 4) & 0xF])
    sb.push(hex_chars[b & 0xF])
  }
  String::from_array(sb)
}