///|
fn fe_zero() -> FixedArray[Int64] {
  FixedArray::make(16, 0L)
}

///|
fn fe_copy(dst : FixedArray[Int64], src : FixedArray[Int64]) -> Unit {
  for i in 0..<16 {
    dst[i] = src[i]
  }
}

///|
fn fe_carry(o : FixedArray[Int64]) -> Unit {
  for i in 0..<16 {
    o[i] = o[i] + 65536L
    let c = o[i] >> 16
    if i < 15 {
      o[i + 1] = o[i + 1] + c - 1L
    } else {
      o[0] = o[0] + 38L * (c - 1L)
    }
    o[i] = o[i] - (c << 16)
  }
}

///|
/// Constant-time conditional swap between field elements `p` and `q` when `b == 1`.
fn fe_cswap(p : FixedArray[Int64], q : FixedArray[Int64], b : Int64) -> Unit {
  let mask = (b - 1L).lnot()
  for i in 0..<16 {
    let t = mask & (p[i] ^ q[i])
    p[i] = p[i] ^ t
    q[i] = q[i] ^ t
  }
}

///|
fn fe_add(
  out : FixedArray[Int64],
  a : FixedArray[Int64],
  b : FixedArray[Int64],
) -> Unit {
  for i in 0..<16 {
    out[i] = a[i] + b[i]
  }
}

///|
fn fe_sub(
  out : FixedArray[Int64],
  a : FixedArray[Int64],
  b : FixedArray[Int64],
) -> Unit {
  for i in 0..<16 {
    out[i] = a[i] - b[i]
  }
}

///|
fn fe_mul(
  out : FixedArray[Int64],
  a : FixedArray[Int64],
  b : FixedArray[Int64],
) -> Unit {
  let t = FixedArray::make(31, 0L)
  for i in 0..<16 {
    for j in 0..<16 {
      t[i + j] = t[i + j] + a[i] * b[j]
    }
  }
  for i in 0..<15 {
    t[i] = t[i] + 38L * t[i + 16]
  }
  for i in 0..<16 {
    out[i] = t[i]
  }
  fe_carry(out)
  fe_carry(out)
}

///|
fn fe_sq(out : FixedArray[Int64], a : FixedArray[Int64]) -> Unit {
  fe_mul(out, a, a)
}

///|
fn fe_inv(out : FixedArray[Int64], inp : FixedArray[Int64]) -> Unit {
  let c = fe_zero()
  fe_copy(c, inp)
  for i = 253; i >= 0; i = i - 1 {
    fe_sq(c, c)
    if i != 2 && i != 4 {
      fe_mul(c, c, inp)
    }
  }
  fe_copy(out, c)
}

///|
fn fe_unpack(out : FixedArray[Int64], bytes32 : BytesView) -> Unit {
  for i in 0..<16 {
    out[i] = bytes32[2 * i].to_int64() | (bytes32[2 * i + 1].to_int64() << 8)
  }
  out[15] = out[15] & 0x7fffL
}

///|
fn fe_pack(inp : FixedArray[Int64]) -> Bytes {
  let t = fe_zero()
  let m = fe_zero()
  fe_copy(t, inp)
  fe_carry(t)
  fe_carry(t)
  fe_carry(t)
  for _ in 0..<2 {
    m[0] = t[0] - 0xffedL
    for i in 1..<15 {
      m[i] = t[i] - 0xffffL - ((m[i - 1] >> 16) & 1L)
      m[i - 1] = m[i - 1] & 0xffffL
    }
    m[15] = t[15] - 0x7fffL - ((m[14] >> 16) & 1L)
    let b = (m[15] >> 16) & 1L
    m[14] = m[14] & 0xffffL
    fe_cswap(t, m, 1L - b)
  }
  let out = FixedArray::make(32, b'\x00')
  for i in 0..<16 {
    out[2 * i] = (t[i] & 0xffL).to_byte()
    out[2 * i + 1] = ((t[i] >> 8) & 0xffL).to_byte()
  }
  Bytes::from_array(out)
}

///|
/// Clamp a 32-byte random secret into a canonical X25519 private scalar (RFC 7748 §5).
pub fn clamp_x25519_private_key(raw32 : BytesView) -> Bytes raise CryptoError {
  if raw32.length() != 32 {
    raise CryptoError::InvalidKeyLength(expected=32, actual=raw32.length())
  }
  let z = FixedArray::make(32, b'\x00')
  for i in 0..<32 {
    z[i] = raw32[i]
  }
  z[0] = (z[0].to_uint() & 248U).to_byte()
  z[31] = ((z[31].to_uint() & 127U) | 64U).to_byte()
  Bytes::from_array(z)
}

///|
/// Raw RFC 7748 `X25519(k, u)` Montgomery ladder (does not reject all-zero output).
pub fn x25519_raw(
  scalar32 : BytesView,
  u_coord32 : BytesView,
) -> Bytes raise CryptoError {
  if scalar32.length() != 32 {
    raise CryptoError::InvalidKeyLength(expected=32, actual=scalar32.length())
  }
  if u_coord32.length() != 32 {
    raise CryptoError::InvalidKeyLength(expected=32, actual=u_coord32.length())
  }
  let z = clamp_x25519_private_key(scalar32)
  let x1 = fe_zero()
  fe_unpack(x1, u_coord32)

  let x2 = fe_zero()
  x2[0] = 1L
  let z2 = fe_zero()
  let x3 = fe_zero()
  fe_copy(x3, x1)
  let z3 = fe_zero()
  z3[0] = 1L

  let a = fe_zero()
  let aa = fe_zero()
  let b = fe_zero()
  let bb = fe_zero()
  let e = fe_zero()
  let c = fe_zero()
  let d = fe_zero()
  let da = fe_zero()
  let cb = fe_zero()
  let a24 = fe_zero()
  a24[0] = 0xdb41L
  a24[1] = 1L

  let mut swap = 0L
  for pos = 254; pos >= 0; pos = pos - 1 {
    let byte_idx = pos >> 3
    let bit_idx = pos & 7
    let kt = (z[byte_idx].to_int64() >> bit_idx) & 1L
    swap = swap ^ kt
    fe_cswap(x2, x3, swap)
    fe_cswap(z2, z3, swap)
    swap = kt

    fe_add(a, x2, z2)
    fe_sq(aa, a)
    fe_sub(b, x2, z2)
    fe_sq(bb, b)
    fe_sub(e, aa, bb)
    fe_add(c, x3, z3)
    fe_sub(d, x3, z3)
    fe_mul(da, d, a)
    fe_mul(cb, c, b)
    fe_add(x3, da, cb)
    fe_sq(x3, x3)
    fe_sub(z3, da, cb)
    fe_sq(z3, z3)
    fe_mul(z3, z3, x1)
    fe_mul(x2, aa, bb)
    fe_mul(z2, e, a24)
    fe_add(z2, aa, z2)
    fe_mul(z2, e, z2)
  }
  fe_cswap(x2, x3, swap)
  fe_cswap(z2, z3, swap)

  fe_inv(z2, z2)
  fe_mul(x2, x2, z2)
  fe_pack(x2)
}

///|
/// WireGuard X25519 Diffie-Hellman shared secret derivation (rejects low-order/all-zero shared secrets per RFC 7748 §6.1).
pub fn x25519_dh(
  private_key32 : BytesView,
  peer_public_key32 : BytesView,
) -> Bytes raise CryptoError {
  let shared = x25519_raw(private_key32, peer_public_key32)
  if ct_is_zero(shared) {
    raise CryptoError::LowOrderPoint
  }
  shared
}

///|
/// Derive a 32-byte X25519 public key from a 32-byte private key using the basepoint `u = 9`.
pub fn x25519_public_key(private_key32 : BytesView) -> Bytes raise CryptoError {
  let basepoint = FixedArray::make(32, b'\x00')
  basepoint[0] = b'\x09'
  x25519_raw(private_key32, Bytes::from_array(basepoint))
}