///|
/// Prime field F_p arithmetic for Curve25519 / Ristretto255 where p = 2^255 - 19.
/// Uses 8 x 32-bit little-endian limbs with UInt64 intermediate products and
/// constant-time reduction, selection, and inverse square root (RFC 9496 §4.2).

///|
/// p = 2^255 - 19
let fe_p : FixedArray[UInt32] = [
  0xFFFFFFEDU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU,
  0x7FFFFFFFU,
]

///|
/// Edwards parameter d = -121665 / 121666 mod p
let fe_d : FixedArray[UInt32] = [
  0x135978A3U, 0x75EB4DCAU, 0x4141D8ABU, 0x00700A4DU, 0x7779E898U, 0x8CC74079U, 0x2B6FFE73U,
  0x52036CEEU,
]

///|
/// 2 * d mod p (used in complete twisted Edwards extended addition)
let fe_2d : FixedArray[UInt32] = [
  0x26B2F159U, 0xEBD69B94U, 0x8283B156U, 0x00E0149AU, 0xEEF3D130U, 0x198E80F2U, 0x56DFFCE7U,
  0x2406D9DCU,
]

///|
/// RFC 9496 §4.1: SQRT_M1 = sqrt(-1) mod p (non-negative / even)
let fe_sqrt_m1 : FixedArray[UInt32] = [
  0x4A0EA0B0U, 0xC4EE1B27U, 0xAD2FE478U, 0x2F431806U, 0x3DFBD7A7U, 0x2B4D0099U, 0x4FC1DF0BU,
  0x2B832480U,
]

///|
/// RFC 9496 §4.1: INVSQRT_A_MINUS_D = 1 / sqrt(a - d) = 1 / sqrt(-1 - d) mod p
let fe_invsqrt_a_minus_d : FixedArray[UInt32] = [
  0x7FA2BF03U, 0x66370255U, 0xA5BE8D41U, 0x62D0E9E8U, 0x01FE27BFU, 0xE93D846EU, 0x3050035DU,
  0x079376FAU,
]

///|
/// RFC 9496 §4.1: ONE_MINUS_D_SQ = (1 - d^2) mod p
let fe_one_minus_d_sq : FixedArray[UInt32] = [
  0x945FC176U, 0xE27C09C1U, 0xCD5E350FU, 0x2C81A138U, 0xBE70DFE4U, 0x9994ABDDU, 0xB2B3E0D7U,
  0x029072A8U,
]

///|
/// RFC 9496 §4.1: D_MINUS_ONE_SQ = (d - 1)^2 mod p
let fe_d_minus_one_sq : FixedArray[UInt32] = [
  0x44ED4D20U, 0x31AD5AAAU, 0xB01E1999U, 0xD29E4A2CU, 0x529B4EEBU, 0x4CDCD32FU, 0xF66C2241U,
  0x5968B37AU,
]

///|
/// RFC 9496 §4.1: SQRT_AD_MINUS_ONE = sqrt(a * d - 1) mod p (RFC 9496 sign)
let fe_sqrt_ad_minus_one : FixedArray[UInt32] = [
  0x497B2E1BU, 0x7E97F6A0U, 0x1B7854BDU, 0xAF9D8E0CU, 0x31F5D1FDU, 0x0F3CFCC9U, 0x2B8348ACU,
  0x376931BFU,
]

///|
/// Canonical field element in [0, 2^255 - 20], 8 x 32-bit little-endian limbs.
#derive(Debug)
priv struct Fe {
  limbs : FixedArray[UInt32]
}

///|
fn fe_zero() -> Fe {
  { limbs: FixedArray::make(8, 0U), }
}

///|
fn fe_one() -> Fe {
  { limbs: [1U, 0U, 0U, 0U, 0U, 0U, 0U, 0U], }
}

///|
fn fe_from_limbs(arr : FixedArray[UInt32]) -> Fe {
  let out = FixedArray::make(8, 0U)
  for i = 0; i < 8; i = i + 1 {
    out[i] = arr[i]
  }
  { limbs: out, }
}

///|
/// Adds two 8-limb unsigned integers and returns `(sum, carry_out)`.
fn raw_add8(
  a : FixedArray[UInt32],
  b : FixedArray[UInt32],
) -> (FixedArray[UInt32], UInt32) {
  let out = FixedArray::make(8, 0U)
  let mut carry = 0UL
  for i = 0; i < 8; i = i + 1 {
    let s = a[i].to_uint64() + b[i].to_uint64() + carry
    out[i] = (s & 0xFFFFFFFFUL).to_uint()
    carry = s >> 32
  }
  (out, carry.to_uint())
}

///|
/// Subtracts `b` from `a` (8 limbs) and returns `(diff, borrow_out)` (0U or 1U).
fn raw_sub8(
  a : FixedArray[UInt32],
  b : FixedArray[UInt32],
) -> (FixedArray[UInt32], UInt32) {
  let out = FixedArray::make(8, 0U)
  let mut borrow = 0UL
  for i = 0; i < 8; i = i + 1 {
    let ai = a[i].to_uint64()
    let bi = b[i].to_uint64() + borrow
    if ai >= bi {
      out[i] = (ai - bi).to_uint()
      borrow = 0UL
    } else {
      out[i] = ((1UL << 32) + ai - bi).to_uint()
      borrow = 1UL
    }
  }
  (out, borrow.to_uint())
}

///|
/// Full 256 x 256 -> 512-bit unsigned multiplication (16 little-endian 32-bit limbs).
fn raw_mul512(
  a : FixedArray[UInt32],
  b : FixedArray[UInt32],
) -> FixedArray[UInt32] {
  let prod = FixedArray::make(16, 0U)
  for i = 0; i < 8; i = i + 1 {
    let ai = a[i].to_uint64()
    let mut carry = 0UL
    for j = 0; j < 8; j = j + 1 {
      let s = prod[i + j].to_uint64() + ai * b[j].to_uint64() + carry
      prod[i + j] = (s & 0xFFFFFFFFUL).to_uint()
      carry = s >> 32
    }
    prod[i + 8] = carry.to_uint()
  }
  prod
}

///|
/// Constant-time selection: returns `a` if `cond == 1U`, `b` if `cond == 0U`.
fn fe_ct_select(cond : UInt32, a : Fe, b : Fe) -> Fe {
  let out = FixedArray::make(8, 0U)
  for i = 0; i < 8; i = i + 1 {
    out[i] = @ct.ct_select_u32(cond, a.limbs[i], b.limbs[i])
  }
  { limbs: out, }
}

///|
/// Constant-time check `a == 0` returning `1U` or `0U`.
fn fe_is_zero_ct(a : Fe) -> UInt32 {
  let mut acc = 0U
  for i = 0; i < 8; i = i + 1 {
    acc = acc | a.limbs[i]
  }
  @ct.ct_is_zero_u32(acc)
}

///|
/// Constant-time equality `a == b` returning `1U` or `0U`.
fn fe_eq_ct(a : Fe, b : Fe) -> UInt32 {
  let mut diff = 0U
  for i = 0; i < 8; i = i + 1 {
    diff = diff | (a.limbs[i] ^ b.limbs[i])
  }
  @ct.ct_is_zero_u32(diff)
}

///|
/// RFC 9496 §4.1: IS_NEGATIVE(e) is 1U iff canonical LSB of `e` is 1 (odd).
fn fe_is_negative_ct(a : Fe) -> UInt32 {
  a.limbs[0] & 1U
}

///|
/// Constant-time canonicalization of `a < 2*p` into `[0, p - 1]`.
fn fe_reduce_once(limbs : FixedArray[UInt32]) -> Fe {
  let (sub, borrow) = raw_sub8(limbs, fe_p)
  fe_ct_select(1U - borrow, { limbs: sub, }, { limbs, })
}

///|
fn fe_add(a : Fe, b : Fe) -> Fe {
  let (sum, _) = raw_add8(a.limbs, b.limbs)
  // Since a, b < 2^255 - 19, sum < 2^256 - 38 (no carry out of bit 255), and sum < 2*p.
  fe_reduce_once(sum)
}

///|
fn fe_sub(a : Fe, b : Fe) -> Fe {
  let (diff, borrow) = raw_sub8(a.limbs, b.limbs)
  let (added, _) = raw_add8(diff, fe_p)
  fe_ct_select(borrow, { limbs: added, }, { limbs: diff, })
}

///|
fn fe_neg(a : Fe) -> Fe {
  let (diff, _) = raw_sub8(fe_p, a.limbs)
  fe_ct_select(fe_is_zero_ct(a), fe_zero(), { limbs: diff, })
}

///|
/// RFC 9496 §4.1: CT_ABS(u) = CT_SELECT(-u, u, IS_NEGATIVE(u)).
fn fe_abs(a : Fe) -> Fe {
  fe_ct_select(fe_is_negative_ct(a), fe_neg(a), a)
}

///|
fn fe_double(a : Fe) -> Fe {
  fe_add(a, a)
}

///|
/// Multiplies two field elements modulo p = 2^255 - 19 using 2^256 === 38 (mod p).
fn fe_mul(a : Fe, b : Fe) -> Fe {
  let c = raw_mul512(a.limbs, b.limbs)
  let r = FixedArray::make(8, 0U)
  // Fold high 256 bits via 2^256 === 38 (mod p)
  let mut carry = 0UL
  for i = 0; i < 8; i = i + 1 {
    let s = c[i].to_uint64() + c[i + 8].to_uint64() * 38UL + carry
    r[i] = (s & 0xFFFFFFFFUL).to_uint()
    carry = s >> 32
  }
  // Extract multiples of 2^255: (carry << 1) | bit_255(r[7])
  let top_255 = (carry << 1) | (r[7] >> 31).to_uint64()
  r[7] = r[7] & 0x7FFFFFFFU
  let mut c2 = top_255 * 19UL
  for i = 0; i < 8; i = i + 1 {
    let s = r[i].to_uint64() + c2
    r[i] = (s & 0xFFFFFFFFUL).to_uint()
    c2 = s >> 32
  }
  // If bit 255 overflowed again, fold one more 19
  let extra = (r[7] >> 31).to_uint64() * 19UL
  r[7] = r[7] & 0x7FFFFFFFU
  let mut c3 = extra
  for i = 0; i < 8; i = i + 1 {
    let s = r[i].to_uint64() + c3
    r[i] = (s & 0xFFFFFFFFUL).to_uint()
    c3 = s >> 32
  }
  // Now r < 2^255 = p + 19; one constant-time conditional subtraction canonicalizes into [0, p - 1].
  fe_reduce_once(r)
}

///|
fn fe_sqr(a : Fe) -> Fe {
  fe_mul(a, a)
}

///|
fn fe_sqr_n(a : Fe, n : Int32) -> Fe {
  let mut cur = a
  for i = 0; i < n; i = i + 1 {
    cur = fe_sqr(cur)
  }
  cur
}

///|
/// Computes a^((p - 5) / 8) = a^(2^252 - 3) mod p using a 251-squaring, 11-mul addition chain.
fn fe_pow_p58(a : Fe) -> Fe {
  let x2 = fe_mul(fe_sqr(a), a) // 2 ones
  let x4 = fe_mul(fe_sqr_n(x2, 2), x2) // 4 ones
  let x5 = fe_mul(fe_sqr(x4), a) // 5 ones
  let x10 = fe_mul(fe_sqr_n(x5, 5), x5) // 10 ones
  let x20 = fe_mul(fe_sqr_n(x10, 10), x10) // 20 ones
  let x40 = fe_mul(fe_sqr_n(x20, 20), x20) // 40 ones
  let x50 = fe_mul(fe_sqr_n(x40, 10), x10) // 50 ones
  let x100 = fe_mul(fe_sqr_n(x50, 50), x50) // 100 ones
  let x200 = fe_mul(fe_sqr_n(x100, 100), x100) // 200 ones
  let x250 = fe_mul(fe_sqr_n(x200, 50), x50) // 250 ones
  fe_mul(fe_sqr_n(x250, 2), a) // 250 ones, 0, 1 = 2^252 - 3
}

///|
/// RFC 9496 §4.2: SQRT_RATIO_M1(u, v) -> (was_square : UInt, r : Fe)
/// Computes non-negative square root of u/v if square, else non-negative square root of i*u/v.
fn fe_sqrt_ratio_m1(u : Fe, v : Fe) -> (UInt32, Fe) {
  let v3 = fe_mul(fe_sqr(v), v)
  let v7 = fe_mul(fe_sqr(v3), v)
  let mut r = fe_mul(fe_mul(u, v3), fe_pow_p58(fe_mul(u, v7)))
  let check = fe_mul(v, fe_sqr(r))
  let sqrt_m1 = fe_from_limbs(fe_sqrt_m1)
  let neg_u = fe_neg(u)
  let correct_sign_sqrt = fe_eq_ct(check, u)
  let flipped_sign_sqrt = fe_eq_ct(check, neg_u)
  let flipped_sign_sqrt_i = fe_eq_ct(check, fe_mul(neg_u, sqrt_m1))
  let r_prime = fe_mul(sqrt_m1, r)
  r = fe_ct_select(flipped_sign_sqrt | flipped_sign_sqrt_i, r_prime, r)
  r = fe_abs(r)
  let was_square = correct_sign_sqrt | flipped_sign_sqrt
  (was_square, r)
}

///|
/// Reads a 32-byte little-endian `BytesView` into an 8-limb array.
fn read_le32_limbs(data : BytesView) -> FixedArray[UInt32] {
  let limbs = FixedArray::make(8, 0U)
  for i = 0; i < 8; i = i + 1 {
    let off = i * 4
    limbs[i] = data[off].to_uint() |
      (data[off + 1].to_uint() << 8) |
      (data[off + 2].to_uint() << 16) |
      (data[off + 3].to_uint() << 24)
  }
  limbs
}

///|
/// Writes an 8-limb array to 32-byte little-endian `Bytes`.
fn write_le32_limbs(limbs : FixedArray[UInt32]) -> Bytes {
  let out = FixedArray::make(32, b'\x00')
  for i = 0; i < 8; i = i + 1 {
    let off = i * 4
    let v = limbs[i]
    out[off] = (v & 0xFFU).to_byte()
    out[off + 1] = ((v >> 8) & 0xFFU).to_byte()
    out[off + 2] = ((v >> 16) & 0xFFU).to_byte()
    out[off + 3] = ((v >> 24) & 0xFFU).to_byte()
  }
  Bytes::from_array(out)
}

///|
/// Strictly decodes a canonical 32-byte little-endian field element (`< p`).
fn fe_from_bytes_canonical(data : BytesView) -> Fe? {
  let limbs = read_le32_limbs(data)
  let (_, borrow) = raw_sub8(limbs, fe_p)
  if borrow == 0U {
    // limbs >= p -> non-canonical
    return None
  }
  Some({ limbs, })
}

///|
/// Decodes 32-byte little-endian bytes for RFC 9496 §4.3.4 MAP:
/// masks bit 255 (`t & (2^255 - 1)`) and reduces mod p.
fn fe_from_bytes_masked_mod_p(data : BytesView) -> Fe {
  let limbs = read_le32_limbs(data)
  limbs[7] = limbs[7] & 0x7FFFFFFFU
  fe_reduce_once(limbs)
}

///|
fn fe_to_bytes(a : Fe) -> Bytes {
  write_le32_limbs(a.limbs)
}