///|
/// Scalar field arithmetic modulo the Ristretto255 / Ed25519 group order
/// l = 2^252 + 27742317777372353535851937790883648493.
/// Uses 8 x 32-bit little-endian limbs with CIOS Montgomery multiplication
/// and constant-time Fermat inversion.

///|
/// Group order l
let sc_l : FixedArray[UInt32] = [
  0x5CF5D3EDU, 0x5812631AU, 0xA2F79CD6U, 0x14DEF9DEU, 0x00000000U, 0x00000000U, 0x00000000U,
  0x10000000U,
]

///|
/// l - 2 (for constant-time Fermat inversion s^(l - 2) mod l)
let sc_l_minus_2 : FixedArray[UInt32] = [
  0x5CF5D3EBU, 0x5812631AU, 0xA2F79CD6U, 0x14DEF9DEU, 0x00000000U, 0x00000000U, 0x00000000U,
  0x10000000U,
]

///|
/// Montgomery constant -l^{-1} mod 2^32
let sc_l0_prime : UInt32 = 0x12547E1BU

///|
/// Montgomery constant R mod l = 2^256 mod l
let sc_r1 : FixedArray[UInt32] = [
  0x8D98951DU, 0xD6EC3174U, 0x737DCF70U, 0xC6EF5BF4U, 0xFFFFFFFEU, 0xFFFFFFFFU, 0xFFFFFFFFU,
  0x0FFFFFFFU,
]

///|
/// Montgomery constant R^2 mod l = 2^512 mod l
let sc_r2 : FixedArray[UInt32] = [
  0x449C0F01U, 0xA40611E3U, 0x68859347U, 0xD00E1BA7U, 0x17F5BE65U, 0xCEEC73D2U, 0x7C309A3DU,
  0x0399411BU,
]

///|
/// 2^128 mod l (used for 64-byte wide reduction)
let sc_2_128 : FixedArray[UInt32] = [
  0x00000000U, 0x00000000U, 0x00000000U, 0x00000000U, 0x00000001U, 0x00000000U, 0x00000000U,
  0x00000000U,
]

///|
/// 2^384 mod l (used for 64-byte wide reduction)
let sc_2_384 : FixedArray[UInt32] = [
  0xA02A6271U, 0x39822129U, 0x5E4FDD95U, 0xB64A7F43U, 0x30A2C131U, 0x7ED9CE5AU, 0xD086329AU,
  0x02106215U,
]

///|
/// Canonical scalar in [0, l - 1], represented as 8 x 32-bit little-endian limbs.
#derive(Debug)
pub struct Scalar {
  priv limbs : FixedArray[UInt32]
}

///|
pub impl Eq for Scalar with fn equal(self, other) {
  let mut diff = 0U
  for i = 0; i < 8; i = i + 1 {
    diff = diff | (self.limbs[i] ^ other.limbs[i])
  }
  diff == 0U
}

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

///|
fn sc_ct_select(cond : UInt32, a : Scalar, b : Scalar) -> Scalar {
  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, }
}

///|
fn sc_is_zero_ct(a : Scalar) -> UInt32 {
  let mut acc = 0U
  for i = 0; i < 8; i = i + 1 {
    acc = acc | a.limbs[i]
  }
  @ct.ct_is_zero_u32(acc)
}

///|
/// Returns the additive identity scalar `0`.
pub fn Scalar::zero() -> Scalar {
  { limbs: FixedArray::make(8, 0U), }
}

///|
/// Returns the multiplicative identity scalar `1`.
pub fn Scalar::one() -> Scalar {
  { limbs: [1U, 0U, 0U, 0U, 0U, 0U, 0U, 0U], }
}

///|
/// Constructs a canonical scalar from a 32-bit unsigned integer `n` (`n < 2^32 < l`).
pub fn Scalar::from_u32(n : UInt32) -> Scalar {
  { limbs: [n, 0U, 0U, 0U, 0U, 0U, 0U, 0U], }
}

///|
/// Constant-time comparison of canonical scalars as integers in `[0, l - 1]`.
/// Returns `-1` if `self < other`, `0` if `self == other`, `1` if `self > other`.
pub fn Scalar::compare(self : Scalar, other : Scalar) -> Int32 {
  let (_, lt) = raw_sub8(self.limbs, other.limbs)
  let (_, gt) = raw_sub8(other.limbs, self.limbs)
  gt.reinterpret_as_int() - lt.reinterpret_as_int()
}

///|
/// Returns `true` iff `self == 0` (constant-time).
pub fn Scalar::is_zero(self : Scalar) -> Bool {
  sc_is_zero_ct(self) == 1U
}

///|
/// Strictly decodes a canonical 32-byte little-endian scalar (`< l`).
pub fn Scalar::from_bytes_canonical(
  bytes : Bytes,
) -> Scalar raise RistrettoError {
  if bytes.length() != 32 {
    raise InvalidLength(bytes.length())
  }
  let limbs = read_le32_limbs(bytes[:])
  let (_, borrow) = raw_sub8(limbs, sc_l)
  if borrow == 0U {
    raise InvalidScalar
  }
  { limbs, }
}

///|
/// Serializes this scalar as 32-byte little-endian canonical `Bytes`.
pub fn Scalar::to_bytes(self : Scalar) -> Bytes {
  write_le32_limbs(self.limbs)
}

///|
/// Constant-time scalar addition modulo l.
pub fn Scalar::add(self : Scalar, other : Scalar) -> Scalar {
  let (sum, carry) = raw_add8(self.limbs, other.limbs)
  let (sub, borrow) = raw_sub8(sum, sc_l)
  let use_sub = carry | (1U - borrow)
  sc_ct_select(use_sub, { limbs: sub, }, { limbs: sum, })
}

///|
/// Constant-time scalar subtraction modulo l.
pub fn Scalar::sub(self : Scalar, other : Scalar) -> Scalar {
  let (diff, borrow) = raw_sub8(self.limbs, other.limbs)
  let (added, _) = raw_add8(diff, sc_l)
  sc_ct_select(borrow, { limbs: added, }, { limbs: diff, })
}

///|
/// Constant-time scalar negation modulo l.
pub fn Scalar::neg(self : Scalar) -> Scalar {
  let (diff, _) = raw_sub8(sc_l, self.limbs)
  sc_ct_select(sc_is_zero_ct(self), Scalar::zero(), { limbs: diff, })
}

///|
/// CIOS Montgomery multiplication modulo l: computes `a * b * R^{-1} mod l`.
fn sc_mont_mul(a : Scalar, b : Scalar) -> Scalar {
  let t = FixedArray::make(10, 0UL)
  let l0p = sc_l0_prime.to_uint64()
  for i = 0; i < 8; i = i + 1 {
    let ai = a.limbs[i].to_uint64()
    let mut carry = 0UL
    for j = 0; j < 8; j = j + 1 {
      let s = t[j] + ai * b.limbs[j].to_uint64() + carry
      t[j] = s & 0xFFFFFFFFUL
      carry = s >> 32
    }
    let s8 = t[8] + carry
    t[8] = s8 & 0xFFFFFFFFUL
    t[9] = s8 >> 32

    let m = (t[0] * l0p) & 0xFFFFFFFFUL
    let mut c2 = (t[0] + m * sc_l[0].to_uint64()) >> 32
    for j = 1; j < 8; j = j + 1 {
      let s = t[j] + m * sc_l[j].to_uint64() + c2
      t[j - 1] = s & 0xFFFFFFFFUL
      c2 = s >> 32
    }
    let s8b = t[8] + c2
    t[7] = s8b & 0xFFFFFFFFUL
    t[8] = t[9] + (s8b >> 32)
    t[9] = 0UL
  }
  let res = FixedArray::make(8, 0U)
  for i = 0; i < 8; i = i + 1 {
    res[i] = t[i].to_uint()
  }
  let (sub, borrow) = raw_sub8(res, sc_l)
  let use_sub = (1U - @ct.ct_is_zero_u64(t[8]).to_uint()) | (1U - borrow)
  sc_ct_select(use_sub, { limbs: sub, }, { limbs: res, })
}

///|
fn sc_to_mont(a : Scalar) -> Scalar {
  sc_mont_mul(a, { limbs: sc_r2, })
}

///|
fn sc_from_mont(a : Scalar) -> Scalar {
  sc_mont_mul(a, Scalar::one())
}

///|
/// Constant-time scalar multiplication modulo l.
pub fn Scalar::mul(self : Scalar, other : Scalar) -> Scalar {
  let am = sc_to_mont(self)
  let bm = sc_to_mont(other)
  sc_from_mont(sc_mont_mul(am, bm))
}

///|
fn sc_get_bit(a : Scalar, bit_idx : Int32) -> UInt32 {
  let limb_idx = bit_idx >> 5
  let shift = bit_idx & 31
  (a.limbs[limb_idx] >> shift) & 1U
}

///|
fn sc_get_nibble(a : Scalar, nib : Int32) -> UInt32 {
  let limb_idx = nib >> 3
  let shift = (nib & 7) << 2
  (a.limbs[limb_idx] >> shift) & 0xFU
}

///|
/// Constant-time multiplicative inverse modulo l via Fermat's Little Theorem `s^(l - 2) mod l`.
/// Raises `ZeroScalar` if `self == 0`.
pub fn Scalar::invert(self : Scalar) -> Scalar raise RistrettoError {
  if self.is_zero() {
    raise ZeroScalar
  }
  let exp : Scalar = { limbs: sc_l_minus_2, }
  let base = sc_to_mont(self)
  let mut acc = sc_from_limbs(sc_r1)
  // Bit 252 is the MSB of l - 2
  for bit = 252; bit >= 0; bit = bit - 1 {
    acc = sc_mont_mul(acc, acc)
    let prod = sc_mont_mul(acc, base)
    acc = sc_ct_select(sc_get_bit(exp, bit), prod, acc)
  }
  sc_from_mont(acc)
}

///|
/// Reads a 16-byte (128-bit) little-endian slice into a canonical `Scalar` (`< 2^128 < l`).
fn sc_from_le16_view(data : BytesView) -> Scalar {
  let limbs = FixedArray::make(8, 0U)
  for i = 0; i < 4; 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, }
}

///|
/// Reduces a 64-byte little-endian unsigned integer modulo group order l (RFC 9497 §4.1).
/// Splits into four 128-bit chunks (< l): `w0 + w1*2^128 + w2*2^256 + w3*2^384 (mod l)`.
pub fn Scalar::from_bytes_mod_order_wide(
  bytes : Bytes,
) -> Scalar raise RistrettoError {
  if bytes.length() != 64 {
    raise InvalidLength(bytes.length())
  }
  let w0 = sc_from_le16_view(bytes[0:16])
  let w1 = sc_from_le16_view(bytes[16:32])
  let w2 = sc_from_le16_view(bytes[32:48])
  let w3 = sc_from_le16_view(bytes[48:64])
  let t1 = w1.mul({ limbs: sc_2_128, })
  let t2 = w2.mul({ limbs: sc_r1, })
  let t3 = w3.mul({ limbs: sc_2_384, })
  w0.add(t1).add(t2).add(t3)
}

///|
/// RFC 9497 §4.1 `HashToScalar(msg, DST)` for `ristretto255-SHA512`:
/// expands 64 uniform bytes via `expand_message_xmd(SHA-512)` and reduces little-endian mod l.
pub fn Scalar::hash_to_scalar(
  msg : Bytes,
  dst : Bytes,
) -> Scalar raise RistrettoError {
  let uniform = @sha2.expand_message_xmd_sha512(msg, dst, 64) catch {
    _ => raise InvalidLength(64)
  }
  Scalar::from_bytes_mod_order_wide(uniform)
}