///|
/// BN254 scalar field F_r modulus (prime subgroup order of G1, G2, GT):
/// r = 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001
pub let fr_modulus : U256 = {
  l0: 0x43e1f593f0000001UL,
  l1: 0x2833e84879b97091UL,
  l2: 0xb85045b68181585dUL,
  l3: 0x30644e72e131a029UL,
}

///|
/// R mod r, where R = 2^256
let fr_r : U256 = {
  l0: 0xac96341c4ffffffbUL,
  l1: 0x36fc76959f60cd29UL,
  l2: 0x666ea36f7879462eUL,
  l3: 0x0e0a77c19a07df2fUL,
}

///|
/// R^2 mod r
let fr_r2 : U256 = {
  l0: 0x1bb8e645ae216da7UL,
  l1: 0x53fe3ab1e35c59e3UL,
  l2: 0x8c49833d53bb8085UL,
  l3: 0x0216d0b17f4e44a5UL,
}

///|
/// -r^-1 mod 2^64
let fr_inv : UInt64 = 0xc2e1f593efffffffUL

///|
/// r - 2 (for Fermat inversion)
let fr_minus_2 : U256 = {
  l0: 0x43e1f593efffffffUL,
  l1: 0x2833e84879b97091UL,
  l2: 0xb85045b68181585dUL,
  l3: 0x30644e72e131a029UL,
}

///|
/// Primitive 2^28-th root of unity in F_r (Montgomery form), derived from 5^((r-1)/2^28) mod r.
let fr_omega_28_mont : U256 = {
  l0: 0x636e735580d13d9cUL,
  l1: 0xa22bf3742445ffd6UL,
  l2: 0x56452ac01eb203d8UL,
  l3: 0x1860ef942963f9e7UL,
}

///|
/// Multiplicative generator of F_r* (5), also used as coset shift for QAP FFT.
pub fn Fr::multiplicative_generator() -> Fr {
  Fr::from_u64(5UL)
}

///|
/// Element of the BN254 scalar prime field F_r, stored in Montgomery representation.
#derive(Debug, Eq, Hash)
pub struct Fr {
  v : U256
}

///|
pub extend Fr with @debug.Debug::{to_repr}

///|
pub extend Fr with Eq::{not_equal, equal}

///|
pub extend Fr with Hash::{hash, hash_combine}

///|
pub fn Fr::zero() -> Fr {
  { v: U256::zero(), }
}

///|
pub fn Fr::one() -> Fr {
  { v: fr_r, }
}

///|
pub fn Fr::is_zero(self : Fr) -> Bool {
  self.v.is_zero()
}

///|
/// Convert a canonical integer u < r into Fr. Raises InvalidFieldElement if u >= r.
pub fn Fr::from_u256(u : U256) -> Fr raise ZkError {
  if u.cmp(fr_modulus) >= 0 {
    raise ZkError::InvalidFieldElement("Fr element >= r: \{u.to_decimal()}")
  }
  { v: mont_mul(u, fr_r2, fr_modulus, fr_inv), }
}

///|
/// Reduce any U256 modulo r into Fr (used for deterministic seeds / hashes).
pub fn Fr::from_u256_mod(u : U256) -> Fr {
  let mut cur = u
  while cur.cmp(fr_modulus) >= 0 {
    let (_, sub) = cur.sub_borrow(fr_modulus)
    cur = sub
  }
  { v: mont_mul(cur, fr_r2, fr_modulus, fr_inv), }
}

///|
pub fn Fr::from_u64(x : UInt64) -> Fr {
  { v: mont_mul(U256::from_u64(x), fr_r2, fr_modulus, fr_inv), }
}

///|
pub fn Fr::from_int(x : Int32) -> Fr {
  if x >= 0 {
    Fr::from_u64(x.to_uint64())
  } else {
    Fr::from_u64((-x).to_uint64()).neg()
  }
}

///|
pub fn Fr::to_u256(self : Fr) -> U256 {
  mont_mul(self.v, U256::one(), fr_modulus, fr_inv)
}

///|
pub fn Fr::from_decimal(s : String) -> Fr raise ZkError {
  Fr::from_u256(U256::from_decimal(s))
}

///|
pub fn Fr::from_hex(s : String) -> Fr raise ZkError {
  Fr::from_u256(U256::from_hex(s))
}

///|
pub fn Fr::from_str(s : String) -> Fr raise ZkError {
  Fr::from_u256(U256::from_str(s))
}

///|
pub fn Fr::to_decimal(self : Fr) -> String {
  self.to_u256().to_decimal()
}

///|
pub fn Fr::to_hex(self : Fr) -> String {
  self.to_u256().to_hex()
}

///|
pub fn Fr::to_be_bytes(self : Fr) -> Bytes {
  self.to_u256().to_be_bytes()
}

///|
pub fn Fr::from_be_bytes(bytes : BytesView) -> Fr raise ZkError {
  Fr::from_u256(U256::from_be_bytes(bytes))
}

///|
pub impl Show for Fr with fn output(self, logger) {
  logger.write_string(self.to_decimal())
}

///|
pub extend Fr with Show::{to_string, output}

///|
pub fn Fr::add(self : Fr, other : Fr) -> Fr {
  let (sum, _) = self.v.add_carry(other.v)
  let (borrow, sub) = sum.sub_borrow(fr_modulus)
  if borrow == 0UL {
    { v: sub, }
  } else {
    { v: sum, }
  }
}

///|
pub fn Fr::sub(self : Fr, other : Fr) -> Fr {
  let (borrow, diff) = self.v.sub_borrow(other.v)
  if borrow == 0UL {
    { v: diff, }
  } else {
    let (wrapped, _) = diff.add_carry(fr_modulus)
    { v: wrapped, }
  }
}

///|
pub fn Fr::neg(self : Fr) -> Fr {
  if self.is_zero() {
    self
  } else {
    let (_, diff) = fr_modulus.sub_borrow(self.v)
    { v: diff, }
  }
}

///|
pub fn Fr::double(self : Fr) -> Fr {
  self.add(self)
}

///|
pub fn Fr::mul(self : Fr, other : Fr) -> Fr {
  { v: mont_mul(self.v, other.v, fr_modulus, fr_inv), }
}

///|
pub fn Fr::square(self : Fr) -> Fr {
  self.mul(self)
}

///|
pub fn Fr::pow(self : Fr, exp : U256) -> Fr {
  let mut res = Fr::one()
  let mut base = self
  let bits = exp.bit_length()
  for i = 0; i < bits; i = i + 1 {
    if exp.bit(i) {
      res = res.mul(base)
    }
    base = base.square()
  }
  res
}

///|
pub fn Fr::inv(self : Fr) -> Fr? {
  if self.is_zero() {
    None
  } else {
    Some(self.pow(fr_minus_2))
  }
}

///|
/// Primitive 2^log_n-th root of unity in F_r (supports 0 <= log_n <= 28).
pub fn Fr::root_of_unity(log_n : Int32) -> Fr raise ZkError {
  if log_n < 0 || log_n > 28 {
    raise ZkError::InvalidInput("FFT log_n must be in 0..28, got \{log_n}")
  }
  let mut w : Fr = { v: fr_omega_28_mont, }
  let mut k = 28
  while k > log_n {
    w = w.square()
    k = k - 1
  }
  w
}

///|
pub impl Add for Fr with fn add(self, other) {
  self.add(other)
}

///|
pub impl Sub for Fr with fn sub(self, other) {
  self.sub(other)
}

///|
pub impl Mul for Fr with fn mul(self, other) {
  self.mul(other)
}

///|
pub impl Neg for Fr with fn neg(self) {
  self.neg()
}