///|
fn rotl32(x : UInt32, n : Int32) -> UInt32 {
  (x << n) | (x >> (32 - n))
}

///|
fn chacha_quarter_round(
  s : FixedArray[UInt32],
  a : Int32,
  b : Int32,
  c : Int32,
  d : Int32,
) -> Unit {
  s[a] = s[a] + s[b]
  s[d] = rotl32(s[d] ^ s[a], 16)
  s[c] = s[c] + s[d]
  s[b] = rotl32(s[b] ^ s[c], 12)
  s[a] = s[a] + s[b]
  s[d] = rotl32(s[d] ^ s[a], 8)
  s[c] = s[c] + s[d]
  s[b] = rotl32(s[b] ^ s[c], 7)
}

///|
fn chacha20_rounds(s : FixedArray[UInt32]) -> Unit {
  for _ in 0..<10 {
    chacha_quarter_round(s, 0, 4, 8, 12)
    chacha_quarter_round(s, 1, 5, 9, 13)
    chacha_quarter_round(s, 2, 6, 10, 14)
    chacha_quarter_round(s, 3, 7, 11, 15)
    chacha_quarter_round(s, 0, 5, 10, 15)
    chacha_quarter_round(s, 1, 6, 11, 12)
    chacha_quarter_round(s, 2, 7, 8, 13)
    chacha_quarter_round(s, 3, 4, 9, 14)
  }
}

///|
fn chacha20_block(
  key : BytesView,
  counter : UInt32,
  nonce12 : BytesView,
  out64 : FixedArray[Byte],
) -> Unit {
  let init = FixedArray::make(16, 0U)
  init[0] = 0x61707865U
  init[1] = 0x3320646eU
  init[2] = 0x79622d32U
  init[3] = 0x6b206574U
  for i in 0..<8 {
    init[4 + i] = read_u32_le(key, i * 4)
  }
  init[12] = counter
  init[13] = read_u32_le(nonce12, 0)
  init[14] = read_u32_le(nonce12, 4)
  init[15] = read_u32_le(nonce12, 8)
  let work = FixedArray::make(16, 0U)
  for i in 0..<16 {
    work[i] = init[i]
  }
  chacha20_rounds(work)
  for i in 0..<16 {
    write_u32_le(out64, i * 4, work[i] + init[i])
  }
}

///|
/// HChaCha20 subkey derivation (draft-irtf-cfrg-xchacha §2.2): 32-byte key + 16-byte nonce -> 32-byte subkey.
pub fn hchacha20(
  key : BytesView,
  nonce16 : BytesView,
) -> Bytes raise CryptoError {
  if key.length() != 32 {
    raise CryptoError::InvalidKeyLength(expected=32, actual=key.length())
  }
  if nonce16.length() != 16 {
    raise CryptoError::InvalidNonceLength(expected=16, actual=nonce16.length())
  }
  let state = FixedArray::make(16, 0U)
  state[0] = 0x61707865U
  state[1] = 0x3320646eU
  state[2] = 0x79622d32U
  state[3] = 0x6b206574U
  for i in 0..<8 {
    state[4 + i] = read_u32_le(key, i * 4)
  }
  for i in 0..<4 {
    state[12 + i] = read_u32_le(nonce16, i * 4)
  }
  chacha20_rounds(state)
  let out = FixedArray::make(32, b'\x00')
  write_u32_le(out, 0, state[0])
  write_u32_le(out, 4, state[1])
  write_u32_le(out, 8, state[2])
  write_u32_le(out, 12, state[3])
  write_u32_le(out, 16, state[12])
  write_u32_le(out, 20, state[13])
  write_u32_le(out, 24, state[14])
  write_u32_le(out, 28, state[15])
  Bytes::from_array(out)
}

///|
/// IETF ChaCha20 XOR stream cipher (RFC 8439 §2.4).
pub fn chacha20_xor(
  key : BytesView,
  counter : UInt32,
  nonce12 : BytesView,
  input : BytesView,
) -> Bytes raise CryptoError {
  if key.length() != 32 {
    raise CryptoError::InvalidKeyLength(expected=32, actual=key.length())
  }
  if nonce12.length() != 12 {
    raise CryptoError::InvalidNonceLength(expected=12, actual=nonce12.length())
  }
  let len = input.length()
  let out = FixedArray::make(len, b'\x00')
  let block = FixedArray::make(64, b'\x00')
  let mut pos = 0
  let mut blk_idx = counter
  while pos < len {
    chacha20_block(key, blk_idx, nonce12, block)
    let rem = len - pos
    let take = if rem < 64 { rem } else { 64 }
    for i in 0.. Unit {
  let len = data.length()
  let mut pos = 0
  let pad_blk = FixedArray::make(17, b'\x00')
  while pos < len {
    let rem = len - pos
    let hibit : UInt64 = if rem >= 16 {
      for i in 0..<16 {
        pad_blk[i] = data[pos + i]
      }
      1UL << 24
    } else {
      for i in 0..<17 {
        pad_blk[i] = b'\x00'
      }
      for i in 0..> 26) | (t1 << 6)) & 0x3ffffffUL
    let b2 = ((t1 >> 20) | (t2 << 12)) & 0x3ffffffUL
    let b3 = ((t2 >> 14) | (t3 << 18)) & 0x3ffffffUL
    let b4 = (t3 >> 8) | hibit | (pad_blk[16].to_uint64() << 24)

    let h0 = h[0] + b0
    let h1 = h[1] + b1
    let h2 = h[2] + b2
    let h3 = h[3] + b3
    let h4 = h[4] + b4

    let d0 = h0 * r0 + h1 * s4 + h2 * s3 + h3 * s2 + h4 * s1
    let d1 = h0 * r1 + h1 * r0 + h2 * s4 + h3 * s3 + h4 * s2
    let d2 = h0 * r2 + h1 * r1 + h2 * r0 + h3 * s4 + h4 * s3
    let d3 = h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * s4
    let d4 = h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0

    let mut c = d0 >> 26
    let mut n0 = d0 & 0x3ffffffUL
    let m1 = d1 + c
    c = m1 >> 26
    let mut n1 = m1 & 0x3ffffffUL
    let m2 = d2 + c
    c = m2 >> 26
    let n2 = m2 & 0x3ffffffUL
    let m3 = d3 + c
    c = m3 >> 26
    let n3 = m3 & 0x3ffffffUL
    let m4 = d4 + c
    c = m4 >> 26
    let n4 = m4 & 0x3ffffffUL
    n0 = n0 + c * 5UL
    c = n0 >> 26
    n0 = n0 & 0x3ffffffUL
    n1 = n1 + c

    h[0] = n0
    h[1] = n1
    h[2] = n2
    h[3] = n3
    h[4] = n4
    pos = pos + (if rem >= 16 { 16 } else { rem })
  }
}

///|
fn poly1305_finish(h : FixedArray[UInt64], key32 : BytesView) -> Bytes {
  let mut h0 = h[0]
  let mut h1 = h[1]
  let mut h2 = h[2]
  let mut h3 = h[3]
  let mut h4 = h[4]

  let mut c = h1 >> 26
  h1 = h1 & 0x3ffffffUL
  h2 = h2 + c
  c = h2 >> 26
  h2 = h2 & 0x3ffffffUL
  h3 = h3 + c
  c = h3 >> 26
  h3 = h3 & 0x3ffffffUL
  h4 = h4 + c
  c = h4 >> 26
  h4 = h4 & 0x3ffffffUL
  h0 = h0 + c * 5UL
  c = h0 >> 26
  h0 = h0 & 0x3ffffffUL
  h1 = h1 + c

  // Compute g = h + 5 and select g in constant time if g4 >= 2^26.
  let mut g0 = h0 + 5UL
  c = g0 >> 26
  g0 = g0 & 0x3ffffffUL
  let mut g1 = h1 + c
  c = g1 >> 26
  g1 = g1 & 0x3ffffffUL
  let mut g2 = h2 + c
  c = g2 >> 26
  g2 = g2 & 0x3ffffffUL
  let mut g3 = h3 + c
  c = g3 >> 26
  g3 = g3 & 0x3ffffffUL
  let g4 = h4 + c - (1UL << 26)

  // If no borrow occurred (h >= 2^130 - 5), top bit of g4 is 0 -> mask = all 1s.
  let mask = (g4 >> 63) - 1UL
  let inv_mask = mask ^ 0xffffffffffffffffUL
  h0 = (h0 & inv_mask) | (g0 & mask)
  h1 = (h1 & inv_mask) | (g1 & mask)
  h2 = (h2 & inv_mask) | (g2 & mask)
  h3 = (h3 & inv_mask) | (g3 & mask)
  h4 = (h4 & inv_mask) | (g4 & mask)

  let w0 = (h0 | (h1 << 26)) & 0xffffffffUL
  let w1 = ((h1 >> 6) | (h2 << 20)) & 0xffffffffUL
  let w2 = ((h2 >> 12) | (h3 << 14)) & 0xffffffffUL
  let w3 = ((h3 >> 18) | (h4 << 8)) & 0xffffffffUL

  let s0 = read_u32_le(key32, 16).to_uint64()
  let s1 = read_u32_le(key32, 20).to_uint64()
  let s2 = read_u32_le(key32, 24).to_uint64()
  let s3 = read_u32_le(key32, 28).to_uint64()

  let f0 = w0 + s0
  let f1 = w1 + s1 + (f0 >> 32)
  let f2 = w2 + s2 + (f1 >> 32)
  let f3 = w3 + s3 + (f2 >> 32)

  let tag = FixedArray::make(16, b'\x00')
  write_u32_le(tag, 0, (f0 & 0xffffffffUL).to_uint())
  write_u32_le(tag, 4, (f1 & 0xffffffffUL).to_uint())
  write_u32_le(tag, 8, (f2 & 0xffffffffUL).to_uint())
  write_u32_le(tag, 12, (f3 & 0xffffffffUL).to_uint())
  Bytes::from_array(tag)
}

///|
fn poly1305_parse_r(
  key32 : BytesView,
) -> (UInt64, UInt64, UInt64, UInt64, UInt64) {
  let t0 = read_u32_le(key32, 0).to_uint64()
  let t1 = read_u32_le(key32, 4).to_uint64()
  let t2 = read_u32_le(key32, 8).to_uint64()
  let t3 = read_u32_le(key32, 12).to_uint64()
  let r0 = t0 & 0x3ffffffUL
  let r1 = ((t0 >> 26) | (t1 << 6)) & 0x3ffff03UL
  let r2 = ((t1 >> 20) | (t2 << 12)) & 0x3ffc0ffUL
  let r3 = ((t2 >> 14) | (t3 << 18)) & 0x3f03fffUL
  let r4 = (t3 >> 8) & 0x00fffffUL
  (r0, r1, r2, r3, r4)
}

///|
/// One-time Poly1305 MAC (RFC 8439 §2.5) with a 32-byte key `(r || s)`.
pub fn poly1305_mac(
  key32 : BytesView,
  msg : BytesView,
) -> Bytes raise CryptoError {
  if key32.length() != 32 {
    raise CryptoError::InvalidKeyLength(expected=32, actual=key32.length())
  }
  let (r0, r1, r2, r3, r4) = poly1305_parse_r(key32)
  let h = FixedArray::make(5, 0UL)
  poly1305_feed_blocks(
    h,
    r0,
    r1,
    r2,
    r3,
    r4,
    r1 * 5UL,
    r2 * 5UL,
    r3 * 5UL,
    r4 * 5UL,
    msg,
  )
  poly1305_finish(h, key32)
}

///|
fn poly1305_aead_tag(
  otk32 : BytesView,
  aad : BytesView,
  ciphertext : BytesView,
) -> Bytes {
  let (r0, r1, r2, r3, r4) = poly1305_parse_r(otk32)
  let s1 = r1 * 5UL
  let s2 = r2 * 5UL
  let s3 = r3 * 5UL
  let s4 = r4 * 5UL
  let h = FixedArray::make(5, 0UL)
  let zero16 = FixedArray::make(16, b'\x00')
  let zeros = Bytes::from_array(zero16)

  if aad.length() > 0 {
    let aad_rem = aad.length() % 16
    let aad_full = aad.length() - aad_rem
    if aad_full > 0 {
      poly1305_feed_blocks(
        h,
        r0,
        r1,
        r2,
        r3,
        r4,
        s1,
        s2,
        s3,
        s4,
        aad[:aad_full],
      )
    }
    if aad_rem > 0 {
      let padded = concat2(aad[aad_full:], zeros[:16 - aad_rem])
      poly1305_feed_blocks(h, r0, r1, r2, r3, r4, s1, s2, s3, s4, padded)
    }
  }

  if ciphertext.length() > 0 {
    let ct_rem = ciphertext.length() % 16
    let ct_full = ciphertext.length() - ct_rem
    if ct_full > 0 {
      poly1305_feed_blocks(
        h,
        r0,
        r1,
        r2,
        r3,
        r4,
        s1,
        s2,
        s3,
        s4,
        ciphertext[:ct_full],
      )
    }
    if ct_rem > 0 {
      let padded = concat2(ciphertext[ct_full:], zeros[:16 - ct_rem])
      poly1305_feed_blocks(h, r0, r1, r2, r3, r4, s1, s2, s3, s4, padded)
    }
  }

  let lens = FixedArray::make(16, b'\x00')
  write_u64_le(lens, 0, aad.length().to_uint64())
  write_u64_le(lens, 8, ciphertext.length().to_uint64())
  poly1305_feed_blocks(
    h,
    r0,
    r1,
    r2,
    r3,
    r4,
    s1,
    s2,
    s3,
    s4,
    Bytes::from_array(lens),
  )
  poly1305_finish(h, otk32)
}

///|
/// IETF ChaCha20-Poly1305 AEAD seal (RFC 8439 §2.8): returns `ciphertext || tag16`.
pub fn chacha20_poly1305_seal(
  key : BytesView,
  nonce12 : BytesView,
  plaintext : BytesView,
  aad : BytesView,
) -> Bytes raise CryptoError {
  if key.length() != 32 {
    raise CryptoError::InvalidKeyLength(expected=32, actual=key.length())
  }
  if nonce12.length() != 12 {
    raise CryptoError::InvalidNonceLength(expected=12, actual=nonce12.length())
  }
  let block0 = FixedArray::make(64, b'\x00')
  chacha20_block(key, 0U, nonce12, block0)
  let otk = Bytes::from_array(block0)[:32]
  let ciphertext = chacha20_xor(key, 1U, nonce12, plaintext)
  let tag = poly1305_aead_tag(otk, aad, ciphertext)
  concat2(ciphertext, tag)
}

///|
/// IETF ChaCha20-Poly1305 AEAD open (RFC 8439 §2.8): verifies 16-byte tag in constant time before decrypting.
pub fn chacha20_poly1305_open(
  key : BytesView,
  nonce12 : BytesView,
  ciphertext_and_tag : BytesView,
  aad : BytesView,
) -> Bytes raise CryptoError {
  if key.length() != 32 {
    raise CryptoError::InvalidKeyLength(expected=32, actual=key.length())
  }
  if nonce12.length() != 12 {
    raise CryptoError::InvalidNonceLength(expected=12, actual=nonce12.length())
  }
  if ciphertext_and_tag.length() < 16 {
    raise CryptoError::AuthenticationFailed
  }
  let ct_len = ciphertext_and_tag.length() - 16
  let ciphertext = ciphertext_and_tag[:ct_len]
  let got_tag = ciphertext_and_tag[ct_len:]
  let block0 = FixedArray::make(64, b'\x00')
  chacha20_block(key, 0U, nonce12, block0)
  let otk = Bytes::from_array(block0)[:32]
  let expected_tag = poly1305_aead_tag(otk, aad, ciphertext)
  if !ct_eq(got_tag, expected_tag) {
    raise CryptoError::AuthenticationFailed
  }
  chacha20_xor(key, 1U, nonce12, ciphertext)
}

///|
fn wg_counter_nonce(counter : UInt64) -> Bytes {
  let n = FixedArray::make(12, b'\x00')
  write_u64_le(n, 4, counter)
  Bytes::from_array(n)
}

///|
/// WireGuard `AEAD(key, counter, plain, authtext)` (§5.4): 12-byte nonce `0x00000000 || le64(counter)`.
pub fn wg_aead_seal(
  key : BytesView,
  counter : UInt64,
  plaintext : BytesView,
  aad : BytesView,
) -> Bytes raise CryptoError {
  chacha20_poly1305_seal(key, wg_counter_nonce(counter), plaintext, aad)
}

///|
/// WireGuard `AEAD^-1(key, counter, cipher, authtext)` (§5.4).
pub fn wg_aead_open(
  key : BytesView,
  counter : UInt64,
  ciphertext_and_tag : BytesView,
  aad : BytesView,
) -> Bytes raise CryptoError {
  chacha20_poly1305_open(
    key,
    wg_counter_nonce(counter),
    ciphertext_and_tag,
    aad,
  )
}

///|
/// XChaCha20-Poly1305 AEAD seal (`XAEAD` in WireGuard §5.4.7, 24-byte nonce).
pub fn xchacha20_poly1305_seal(
  key : BytesView,
  nonce24 : BytesView,
  plaintext : BytesView,
  aad : BytesView,
) -> Bytes raise CryptoError {
  if key.length() != 32 {
    raise CryptoError::InvalidKeyLength(expected=32, actual=key.length())
  }
  if nonce24.length() != 24 {
    raise CryptoError::InvalidNonceLength(expected=24, actual=nonce24.length())
  }
  let subkey = hchacha20(key, nonce24[:16])
  let subnonce = FixedArray::make(12, b'\x00')
  for i in 0..<8 {
    subnonce[4 + i] = nonce24[16 + i]
  }
  chacha20_poly1305_seal(subkey, Bytes::from_array(subnonce), plaintext, aad)
}

///|
/// XChaCha20-Poly1305 AEAD open (`XAEAD^-1` in WireGuard §5.4.7, 24-byte nonce).
pub fn xchacha20_poly1305_open(
  key : BytesView,
  nonce24 : BytesView,
  ciphertext_and_tag : BytesView,
  aad : BytesView,
) -> Bytes raise CryptoError {
  if key.length() != 32 {
    raise CryptoError::InvalidKeyLength(expected=32, actual=key.length())
  }
  if nonce24.length() != 24 {
    raise CryptoError::InvalidNonceLength(expected=24, actual=nonce24.length())
  }
  let subkey = hchacha20(key, nonce24[:16])
  let subnonce = FixedArray::make(12, b'\x00')
  for i in 0..<8 {
    subnonce[4 + i] = nonce24[16 + i]
  }
  chacha20_poly1305_open(
    subkey,
    Bytes::from_array(subnonce),
    ciphertext_and_tag,
    aad,
  )
}