///|
/// IETF RFC 9496 Ristretto255 Prime-Order Group over Curve25519 (p = 2^255 - 19).
/// Extended twisted Edwards coordinates `(X, Y, Z, T)` with complete addition,
/// constant-time 4-bit fixed-window scalar multiplication, canonical encode/decode,
/// Elligator-2 `from_uniform_bytes`, and RFC 9497 `hash_to_group`.

///|
#derive(Debug, Eq)
pub suberror RistrettoError {
  InvalidEncoding
  InvalidScalar
  InvalidLength(Int32)
  ZeroScalar
}

///|
/// Ed25519 standard base point B coordinates.
let ed_bx : FixedArray[UInt32] = [
  0x8F25D51AU, 0xC9562D60U, 0x9525A7B2U, 0x692CC760U, 0xFDD6DC5CU, 0xC0A4E231U, 0xCD6E53FEU,
  0x216936D3U,
]

///|
let ed_by : FixedArray[UInt32] = [
  0x66666658U, 0x66666666U, 0x66666666U, 0x66666666U, 0x66666666U, 0x66666666U, 0x66666666U,
  0x66666666U,
]

///|
let ed_bt : FixedArray[UInt32] = [
  0xA5B7DDA3U, 0x6DDE8AB3U, 0x775152F5U, 0x20F09F80U, 0x64ABE37DU, 0x66EA4E8EU, 0xD78B7665U,
  0x67875F0FU,
]

///|
/// Ristretto255 group element represented internally as an extended twisted
/// Edwards point `(X, Y, Z, T)` with `x = X/Z`, `y = Y/Z`, `x*y = T/Z`.
#derive(Debug)
pub struct Point {
  priv x : Fe
  priv y : Fe
  priv z : Fe
  priv t : Fe
}

///|
pub impl Eq for Point with fn equal(self, other) {
  self.equals(other)
}

///|
/// Returns the Ristretto255 group identity element `(0, 1, 1, 0)`.
pub fn Point::identity() -> Point {
  { x: fe_zero(), y: fe_one(), z: fe_one(), t: fe_zero(), }
}

///|
/// Returns the standard Ristretto255 generator (Ed25519 base point `B`).
pub fn Point::generator() -> Point {
  {
    x: fe_from_limbs(ed_bx),
    y: fe_from_limbs(ed_by),
    z: fe_one(),
    t: fe_from_limbs(ed_bt),
  }
}

///|
fn point_ct_select(cond : UInt32, a : Point, b : Point) -> Point {
  {
    x: fe_ct_select(cond, a.x, b.x),
    y: fe_ct_select(cond, a.y, b.y),
    z: fe_ct_select(cond, a.z, b.z),
    t: fe_ct_select(cond, a.t, b.t),
  }
}

///|
/// RFC 9496 §4.3.3 constant-time equivalence test:
/// `X1 * Y2 == Y1 * X2 || Y1 * Y2 == X1 * X2`.
pub fn Point::equals(self : Point, other : Point) -> Bool {
  let lhs1 = fe_mul(self.x, other.y)
  let rhs1 = fe_mul(self.y, other.x)
  let lhs2 = fe_mul(self.y, other.y)
  let rhs2 = fe_mul(self.x, other.x)
  (fe_eq_ct(lhs1, rhs1) | fe_eq_ct(lhs2, rhs2)) == 1U
}

///|
/// Returns `true` iff `self` represents the Ristretto255 identity element (constant-time).
pub fn Point::is_identity(self : Point) -> Bool {
  self.equals(Point::identity())
}

///|
/// Negates a point on the twisted Edwards curve: `-(X, Y, Z, T) = (-X, Y, Z, -T)`.
pub fn Point::neg(self : Point) -> Point {
  { x: fe_neg(self.x), y: self.y, z: self.z, t: fe_neg(self.t), }
}

///|
/// Complete unified twisted Edwards extended point addition (`a = -1`).
/// Valid for all pairs of points including identity, doubling, and inverses.
pub fn Point::add(self : Point, other : Point) -> Point {
  let a = fe_mul(fe_sub(self.y, self.x), fe_sub(other.y, other.x))
  let b = fe_mul(fe_add(self.y, self.x), fe_add(other.y, other.x))
  let c = fe_mul(fe_from_limbs(fe_2d), fe_mul(self.t, other.t))
  let d = fe_double(fe_mul(self.z, other.z))
  let e = fe_sub(b, a)
  let f = fe_sub(d, c)
  let g = fe_add(d, c)
  let h = fe_add(b, a)
  { x: fe_mul(e, f), y: fe_mul(g, h), z: fe_mul(f, g), t: fe_mul(e, h), }
}

///|
/// Point subtraction `self - other`.
pub fn Point::sub(self : Point, other : Point) -> Point {
  self.add(other.neg())
}

///|
/// Fast dedicated extended twisted Edwards doubling (`a = -1`): 4M + 4S.
fn point_double(p : Point) -> Point {
  let a = fe_sqr(p.x)
  let b = fe_sqr(p.y)
  let c = fe_double(fe_sqr(p.z))
  let h = fe_add(a, b)
  let e = fe_sub(h, fe_sqr(fe_add(p.x, p.y)))
  let g = fe_sub(a, b)
  let f = fe_add(c, g)
  { x: fe_mul(e, f), y: fe_mul(g, h), z: fe_mul(f, g), t: fe_mul(e, h), }
}

///|
/// Constant-time 4-bit fixed-window scalar multiplication `s * self`.
pub fn Point::mul(self : Point, s : Scalar) -> Point {
  // Precompute table[j] = j * self for j in 0..15
  let table : FixedArray[Point] = FixedArray::make(16, Point::identity())
  table[1] = self
  for i = 2; i < 16; i = i + 1 {
    if (i & 1) == 0 {
      table[i] = point_double(table[i >> 1])
    } else {
      table[i] = table[i - 1].add(self)
    }
  }
  // Highest nonzero nibble of canonical scalar (< 2^253) is nibble 63
  let mut acc = Point::identity()
  for nib = 63; nib >= 0; nib = nib - 1 {
    if nib < 63 {
      acc = point_double(acc)
      acc = point_double(acc)
      acc = point_double(acc)
      acc = point_double(acc)
    }
    let idx = sc_get_nibble(s, nib)
    let mut selected = Point::identity()
    for j = 0; j < 16; j = j + 1 {
      let eq = @ct.ct_eq_u32(idx, j.reinterpret_as_uint())
      selected = point_ct_select(eq, table[j], selected)
    }
    acc = acc.add(selected)
  }
  acc
}

///|
/// Constant-time scalar multiplication of the standard generator `s * B`.
pub fn Point::mul_base(s : Scalar) -> Point {
  Point::generator().mul(s)
}

///|
/// RFC 9496 §4.3.2 canonical 32-byte encoding of a Ristretto255 element (constant-time).
pub fn Point::encode(self : Point) -> Bytes {
  let x0 = self.x
  let y0 = self.y
  let z0 = self.z
  let t0 = self.t

  let u1 = fe_mul(fe_add(z0, y0), fe_sub(z0, y0))
  let u2 = fe_mul(x0, y0)
  let (_, invsqrt) = fe_sqrt_ratio_m1(fe_one(), fe_mul(u1, fe_sqr(u2)))
  let den1 = fe_mul(invsqrt, u1)
  let den2 = fe_mul(invsqrt, u2)
  let z_inv = fe_mul(fe_mul(den1, den2), t0)

  let sqrt_m1 = fe_from_limbs(fe_sqrt_m1)
  let ix0 = fe_mul(x0, sqrt_m1)
  let iy0 = fe_mul(y0, sqrt_m1)
  let enchanted_denom = fe_mul(den1, fe_from_limbs(fe_invsqrt_a_minus_d))

  let rotate = fe_is_negative_ct(fe_mul(t0, z_inv))
  let x = fe_ct_select(rotate, iy0, x0)
  let mut y = fe_ct_select(rotate, ix0, y0)
  let den_inv = fe_ct_select(rotate, enchanted_denom, den2)

  let flip_y = fe_is_negative_ct(fe_mul(x, z_inv))
  y = fe_ct_select(flip_y, fe_neg(y), y)
  let s = fe_abs(fe_mul(den_inv, fe_sub(z0, y)))
  fe_to_bytes(s)
}

///|
/// RFC 9496 §4.3.1 strict canonical decoding of a 32-byte Ristretto255 element.
/// Rejects wrong length, non-canonical field elements (>= p), odd/negative values,
/// non-squares, negative `t`, and `y == 0`.
pub fn Point::decode(bytes : Bytes) -> Point raise RistrettoError {
  if bytes.length() != 32 {
    raise InvalidLength(bytes.length())
  }
  let s = match fe_from_bytes_canonical(bytes[:]) {
    Some(v) => v
    None => raise InvalidEncoding
  }
  if fe_is_negative_ct(s) != 0U {
    raise InvalidEncoding
  }
  let ss = fe_sqr(s)
  let u1 = fe_sub(fe_one(), ss)
  let u2 = fe_add(fe_one(), ss)
  let u2_sqr = fe_sqr(u2)
  let d = fe_from_limbs(fe_d)
  let v = fe_sub(fe_neg(fe_mul(d, fe_sqr(u1))), u2_sqr)
  let (was_sq, invsqrt) = fe_sqrt_ratio_m1(fe_one(), fe_mul(v, u2_sqr))
  let den_x = fe_mul(invsqrt, u2)
  let den_y = fe_mul(fe_mul(invsqrt, den_x), v)
  let x = fe_abs(fe_mul(fe_double(s), den_x))
  let y = fe_mul(u1, den_y)
  let t = fe_mul(x, y)
  if was_sq == 0U || fe_is_negative_ct(t) != 0U || fe_is_zero_ct(y) != 0U {
    raise InvalidEncoding
  }
  { x, y, z: fe_one(), t, }
}

///|
/// RFC 9496 §4.3.4 Elligator-2 one-way map `MAP(t)` from 32 bytes to a Ristretto255 element.
fn elligator_map(t_view : BytesView) -> Point {
  let r0 = fe_from_bytes_masked_mod_p(t_view)
  let d = fe_from_limbs(fe_d)
  let sqrt_m1 = fe_from_limbs(fe_sqrt_m1)
  let r = fe_mul(sqrt_m1, fe_sqr(r0))
  let n_s = fe_mul(fe_add(r, fe_one()), fe_from_limbs(fe_one_minus_d_sq))
  let neg_one = fe_neg(fe_one())
  let denom = fe_mul(fe_sub(neg_one, fe_mul(d, r)), fe_add(r, d))

  let (was_sq, s0) = fe_sqrt_ratio_m1(n_s, denom)
  let s_prime = fe_neg(fe_abs(fe_mul(s0, r0)))
  let not_sq = 1U - was_sq
  let s = fe_ct_select(not_sq, s_prime, s0)
  let c = fe_ct_select(not_sq, r, neg_one)

  let n_t = fe_sub(
    fe_mul(fe_mul(c, fe_sub(r, fe_one())), fe_from_limbs(fe_d_minus_one_sq)),
    denom,
  )
  let w0 = fe_mul(fe_double(s), denom)
  let w1 = fe_mul(n_t, fe_from_limbs(fe_sqrt_ad_minus_one))
  let s_sq = fe_sqr(s)
  let w2 = fe_sub(fe_one(), s_sq)
  let w3 = fe_add(fe_one(), s_sq)
  {
    x: fe_mul(w0, w3),
    y: fe_mul(w2, w1),
    z: fe_mul(w1, w3),
    t: fe_mul(w0, w2),
  }
}

///|
/// RFC 9496 §4.3.4 `from_uniform_bytes`: maps 64 uniform bytes to a Ristretto255 element
/// via `MAP(b[0..32]) + MAP(b[32..64])`.
pub fn Point::from_uniform_bytes(bytes : Bytes) -> Point raise RistrettoError {
  if bytes.length() != 64 {
    raise InvalidLength(bytes.length())
  }
  elligator_map(bytes[0:32]).add(elligator_map(bytes[32:64]))
}

///|
/// RFC 9497 §4.1 `HashToGroup(msg, DST)` for `ristretto255-SHA512`:
/// expands 64 uniform bytes via `expand_message_xmd(SHA-512)` and maps via `from_uniform_bytes`.
pub fn Point::hash_to_group(
  msg : Bytes,
  dst : Bytes,
) -> Point raise RistrettoError {
  let uniform = @sha2.expand_message_xmd_sha512(msg, dst, 64) catch {
    _ => raise InvalidLength(64)
  }
  Point::from_uniform_bytes(uniform)
}