///|
/// NIST P-256 (secp256r1) Elliptic Curve Group, SEC1 33-Byte Compressed Encoding,
/// Constant-Time 4-Bit Fixed-Window Scalar Multiplication, and RFC 9380
/// `P256_XMD:SHA-256_SSWU_RO_` Hash-to-Curve.

// ============================================================================
// Curve & RFC 9380 Simplified SWU Constants
// ============================================================================

///|
/// Curve coefficient a = p - 3
let curve_a_u256 : U256 = {
  l0: 0xFFFFFFFCU,
  l1: 0xFFFFFFFFU,
  l2: 0xFFFFFFFFU,
  l3: 0x00000000U,
  l4: 0x00000000U,
  l5: 0x00000000U,
  l6: 0x00000001U,
  l7: 0xFFFFFFFFU,
}

///|
/// Curve coefficient b = 0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B
let curve_b_u256 : U256 = {
  l0: 0x27D2604BU,
  l1: 0x3BCE3C3EU,
  l2: 0xCC53B0F6U,
  l3: 0x651D06B0U,
  l4: 0x769886BCU,
  l5: 0xB3EBBD55U,
  l6: 0xAA3A93E7U,
  l7: 0x5AC635D8U,
}

///|
/// Standard generator G_x = 0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296
let gen_x_u256 : U256 = {
  l0: 0xD898C296U,
  l1: 0xF4A13945U,
  l2: 0x2DEB33A0U,
  l3: 0x77037D81U,
  l4: 0x63A440F2U,
  l5: 0xF8BCE6E5U,
  l6: 0xE12C4247U,
  l7: 0x6B17D1F2U,
}

///|
/// Standard generator G_y = 0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5
let gen_y_u256 : U256 = {
  l0: 0x37BF51F5U,
  l1: 0xCBB64068U,
  l2: 0x6B315ECEU,
  l3: 0x2BCE3357U,
  l4: 0x7C0F9E16U,
  l5: 0x8EE7EB4AU,
  l6: 0xFE1A7F9BU,
  l7: 0x4FE342E2U,
}

///|
/// RFC 9380 §8.2 P-256 SSWU parameter Z = -10 mod p
let sswu_z_u256 : U256 = {
  l0: 0xFFFFFFF5U,
  l1: 0xFFFFFFFFU,
  l2: 0xFFFFFFFFU,
  l3: 0x00000000U,
  l4: 0x00000000U,
  l5: 0x00000000U,
  l6: 0x00000001U,
  l7: 0xFFFFFFFFU,
}

///|
/// RFC 9380 §6.6.2 SSWU constant c1 = -B / A mod p
let sswu_c1_u256 : U256 = {
  l0: 0x629B756EU,
  l1: 0x6944BEBFU,
  l2: 0x441BE5A7U,
  l3: 0xCC5F023BU,
  l4: 0x7CDD823EU,
  l5: 0x3BF93F1CU,
  l6: 0xE368DBF8U,
  l7: 0x73976747U,
}

///|
/// RFC 9380 §6.6.2 SSWU exceptional constant c2 = B / (Z * A) mod p
let sswu_c2_u256 : U256 = {
  l0: 0x2375F224U,
  l1: 0xBDBA1313U,
  l2: 0x20693090U,
  l3: 0x146FE6A0U,
  l4: 0xD94959D3U,
  l5: 0x6C65B982U,
  l6: 0x96BDAF99U,
  l7: 0xA528BD86U,
}

///|
/// NIST P-256 curve point in Jacobian projective coordinates `(X, Y, Z)`
/// representing `(X / Z^2, Y / Z^3)`, with `Z == 0` denoting the identity.
#derive(Debug)
pub struct Point {
  priv x : Fe
  priv y : Fe
  priv z : Fe
}

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

///|
/// Returns the group identity (point at infinity).
pub fn Point::identity() -> Point {
  { x: fp_zero(), y: fp_one(), z: fp_zero(), }
}

///|
/// Returns the standard NIST P-256 base point `G`.
pub fn Point::generator() -> Point {
  { x: fp_from_u256(gen_x_u256), y: fp_from_u256(gen_y_u256), z: fp_one(), }
}

///|
/// Returns `true` if `self` is the identity element.
pub fn Point::is_identity(self : Point) -> Bool {
  fp_is_zero(self.z) == 1U
}

///|
/// Constant-time point equality in Jacobian coordinates.
pub fn Point::equals(self : Point, other : Point) -> Bool {
  let p_inf = fp_is_zero(self.z)
  let q_inf = fp_is_zero(other.z)
  let both_inf = p_inf & q_inf
  let z1z1 = fp_sqr(self.z)
  let z2z2 = fp_sqr(other.z)
  let x_eq = fp_eq(fp_mul(self.x, z2z2), fp_mul(other.x, z1z1))
  let y1z2 = fp_mul(self.y, fp_mul(other.z, z2z2))
  let y2z1 = fp_mul(other.y, fp_mul(self.z, z1z1))
  let y_eq = fp_eq(y1z2, y2z1)
  let neither_inf = (1U - p_inf) & (1U - q_inf)
  (both_inf | (neither_inf & x_eq & y_eq)) == 1U
}

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

///|
/// Negates a point: `-(X, Y, Z) = (X, -Y, Z)`.
pub fn Point::neg(self : Point) -> Point {
  { x: self.x, y: fp_neg(self.y), z: self.z, }
}

///|
/// Constant-time Jacobian doubling for curves with `a = -3` (`dbl-2001-b`).
/// Automatically preserves identity (`Z == 0 => Z3 == 0`).
fn point_double(p : Point) -> Point {
  let delta = fp_sqr(p.z)
  let gamma = fp_sqr(p.y)
  let beta = fp_mul(p.x, gamma)
  // alpha = 3 * (X1 - delta) * (X1 + delta)
  let t1 = fp_sub(p.x, delta)
  let t2 = fp_add(p.x, delta)
  let prod = fp_mul(t1, t2)
  let alpha = fp_add(fp_add(prod, prod), prod)
  // X3 = alpha^2 - 8 * beta
  let b2 = fp_add(beta, beta)
  let b4 = fp_add(b2, b2)
  let b8 = fp_add(b4, b4)
  let x3 = fp_sub(fp_sqr(alpha), b8)
  // Z3 = (Y1 + Z1)^2 - gamma - delta = 2 * Y1 * Z1
  let yz = fp_mul(p.y, p.z)
  let z3 = fp_add(yz, yz)
  // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2
  let g2 = fp_sqr(gamma)
  let g4 = fp_add(g2, g2)
  let g8 = fp_add(g4, g4)
  let g8_2 = fp_add(g8, g8)
  let y3 = fp_sub(fp_mul(alpha, fp_sub(b4, x3)), g8_2)
  { x: x3, y: y3, z: z3, }
}

///|
/// Complete, branchless constant-time Jacobian point addition handling all
/// cases (`P == inf`, `Q == inf`, `P == Q`, `P == -Q`, and general `P != +-Q`).
pub fn Point::add(self : Point, other : Point) -> Point {
  let p_inf = fp_is_zero(self.z)
  let q_inf = fp_is_zero(other.z)
  let z1z1 = fp_sqr(self.z)
  let z2z2 = fp_sqr(other.z)
  let u1 = fp_mul(self.x, z2z2)
  let u2 = fp_mul(other.x, z1z1)
  let s1 = fp_mul(self.y, fp_mul(other.z, z2z2))
  let s2 = fp_mul(other.y, fp_mul(self.z, z1z1))
  let h = fp_sub(u2, u1)
  let r = fp_sub(s2, s1)
  let h_zero = fp_is_zero(h)
  let r_zero = fp_is_zero(r)
  let hh = fp_sqr(h)
  let hhh = fp_mul(h, hh)
  let v = fp_mul(u1, hh)
  let x_add = fp_sub(fp_sub(fp_sqr(r), hhh), fp_add(v, v))
  let y_add = fp_sub(fp_mul(r, fp_sub(v, x_add)), fp_mul(s1, hhh))
  let z_add = fp_mul(fp_mul(self.z, other.z), h)
  let add_pt : Point = { x: x_add, y: y_add, z: z_add, }
  let dbl_pt = point_double(self)
  // If h == 0 and r == 0 -> P == Q -> use doubling; if h == 0 and r != 0 -> z_add == 0 (identity)
  let res1 = point_ct_select(h_zero & r_zero, dbl_pt, add_pt)
  let res2 = point_ct_select(p_inf, other, res1)
  point_ct_select(q_inf, self, res2)
}

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

///|
/// Constant-time 4-bit fixed-window scalar multiplication `s * self`.
/// Performs a full linear scan over the 16-entry precomputed table on every
/// nibble with zero secret-dependent branches or table indexing.
pub fn Point::mul(self : Point, s : Scalar) -> Point {
  let tbl = FixedArray::make(16, Point::identity())
  tbl[1] = self
  for i = 2; i < 16; i = i + 1 {
    tbl[i] = tbl[i - 1].add(self)
  }
  let s_bytes = s.to_bytes()
  let mut acc = Point::identity()
  for byte_idx = 0; byte_idx < 32; byte_idx = byte_idx + 1 {
    let b = s_bytes[byte_idx].to_uint()
    // High nibble then low nibble
    for shift = 4; shift >= 0; shift = shift - 4 {
      acc = point_double(acc)
      acc = point_double(acc)
      acc = point_double(acc)
      acc = point_double(acc)
      let nib = (b >> shift) & 0xFU
      let mut selected = Point::identity()
      for j = 0; j < 16; j = j + 1 {
        let is_j = @ct.ct_eq_u32(nib, j.reinterpret_as_uint())
        selected = point_ct_select(is_j, tbl[j], selected)
      }
      acc = acc.add(selected)
    }
  }
  acc
}

///|
/// Constant-time scalar multiplication of the NIST P-256 base point `s * G`.
pub fn Point::mul_base(s : Scalar) -> Point {
  Point::generator().mul(s)
}

// ============================================================================
// SEC1 33-Byte Compressed Point Encoding & Decoding (RFC 9497 §4.3)
// ============================================================================

///|
/// Encodes a non-identity point in 33-byte SEC1 compressed format (`0x02/0x03 || X`).
/// Raises `IdentityElement` if `self` is the point at infinity.
pub fn Point::encode_compressed(self : Point) -> Bytes raise P256Error {
  if self.is_identity() {
    raise IdentityElement
  }
  let z_inv = fp_inv(self.z)
  let z_inv2 = fp_sqr(z_inv)
  let z_inv3 = fp_mul(z_inv2, z_inv)
  let x_aff = fp_mul(self.x, z_inv2)
  let y_aff = fp_mul(self.y, z_inv3)
  let x_bytes = u256_to_be_bytes(fp_to_u256(x_aff))
  let out = FixedArray::make(33, b'\x00')
  out[0] = if fp_sgn0(y_aff) == 1U { b'\x03' } else { b'\x02' }
  for i = 0; i < 32; i = i + 1 {
    out[1 + i] = x_bytes[i]
  }
  Bytes::from_array(out)
}

///|
/// Strictly decodes a 33-byte SEC1 compressed point (`0x02/0x03 || X`).
/// Rejects wrong lengths, uncompressed/identity prefixes (`0x00`/`0x04`),
/// non-canonical `X >= p`, and off-curve points.
pub fn Point::decode_compressed(data : Bytes) -> Point raise P256Error {
  if data.length() != 33 {
    raise InvalidLength(data.length())
  }
  let prefix = data[0]
  if prefix != b'\x02' && prefix != b'\x03' {
    raise InvalidEncoding
  }
  let x_u = u256_from_be_view(data[1:33])
  if u256_gte(x_u, p_mod) == 1U {
    raise InvalidEncoding
  }
  let x = fp_from_u256(x_u)
  let fe_a = fp_from_u256(curve_a_u256)
  let fe_b = fp_from_u256(curve_b_u256)
  // rhs = x^3 + a*x + b
  let rhs = fp_add(fp_add(fp_mul(fp_sqr(x), x), fp_mul(fe_a, x)), fe_b)
  let y_cand = fp_sqrt(rhs)
  if fp_eq(fp_sqr(y_cand), rhs) == 0U {
    raise InvalidEncoding
  }
  let want_odd : UInt32 = if prefix == b'\x03' { 1U } else { 0U }
  let flip = fp_sgn0(y_cand) ^ want_odd
  let y = fp_ct_select(flip, fp_neg(y_cand), y_cand)
  { x, y, z: fp_one(), }
}

// ============================================================================
// RFC 9380 `P256_XMD:SHA-256_SSWU_RO_` Hash-to-Curve (Simplified SWU, Z = -10)
// ============================================================================

///|
/// Constant-time RFC 9380 §6.6.2 Simplified SWU map `u in F_p -> (x, y) on P-256`.
fn map_to_curve_sswu(u : Fe) -> Point {
  let fe_a = fp_from_u256(curve_a_u256)
  let fe_b = fp_from_u256(curve_b_u256)
  let fe_z = fp_from_u256(sswu_z_u256)
  let fe_c1 = fp_from_u256(sswu_c1_u256)
  let fe_c2 = fp_from_u256(sswu_c2_u256)
  let u2 = fp_sqr(u)
  let zu2 = fp_mul(fe_z, u2)
  let z2u4 = fp_sqr(zu2)
  // tv1 = inv0(Z^2 * u^4 + Z * u^2)
  let tv1 = fp_inv(fp_add(z2u4, zu2))
  let tv1_zero = fp_is_zero(tv1)
  // x1 = (-B/A) * (1 + tv1), or B/(Z*A) when tv1 == 0
  let x1_normal = fp_mul(fe_c1, fp_add(fp_one(), tv1))
  let x1 = fp_ct_select(tv1_zero, fe_c2, x1_normal)
  let gx1 = fp_add(fp_add(fp_mul(fp_sqr(x1), x1), fp_mul(fe_a, x1)), fe_b)
  let x2 = fp_mul(zu2, x1)
  let gx2 = fp_add(fp_add(fp_mul(fp_sqr(x2), x2), fp_mul(fe_a, x2)), fe_b)
  let y1 = fp_sqrt(gx1)
  let is_gx1_sq = fp_eq(fp_sqr(y1), gx1)
  let y2 = fp_sqrt(gx2)
  let x = fp_ct_select(is_gx1_sq, x1, x2)
  let y_raw = fp_ct_select(is_gx1_sq, y1, y2)
  // Ensure sgn0(u) == sgn0(y) in constant time
  let flip = fp_sgn0(u) ^ fp_sgn0(y_raw)
  let y = fp_ct_select(flip, fp_neg(y_raw), y_raw)
  { x, y, z: fp_one(), }
}

///|
/// RFC 9380 `P256_XMD:SHA-256_SSWU_RO_` hash-to-curve:
/// expands `(msg, dst)` to 96 uniform bytes via `expand_message_xmd(SHA-256)`,
/// maps two 48-byte elements `u0, u1 mod p` through Simplified SWU (`Z = -10`),
/// and returns `Q0 + Q1`.
pub fn Point::hash_to_group(msg : Bytes, dst : Bytes) -> Point raise P256Error {
  let uniform = @sha2.expand_message_xmd_sha256(msg, dst, 96) catch {
    @sha2.InvalidLength(len) => raise InvalidLength(len)
  }
  let u0 = fp_from_be48(uniform[0:48])
  let u1 = fp_from_be48(uniform[48:96])
  let q0 = map_to_curve_sswu(u0)
  let q1 = map_to_curve_sswu(u1)
  q0.add(q1)
}