///|
/// BN254 base field F_p modulus:
/// p = 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47
pub let fp_modulus : U256 = {
  l0: 0x3c208c16d87cfd47UL,
  l1: 0x97816a916871ca8dUL,
  l2: 0xb85045b68181585dUL,
  l3: 0x30644e72e131a029UL,
}

///|
/// R mod p, where R = 2^256
let fp_r : U256 = {
  l0: 0xd35d438dc58f0d9dUL,
  l1: 0x0a78eb28f5c70b3dUL,
  l2: 0x666ea36f7879462cUL,
  l3: 0x0e0a77c19a07df2fUL,
}

///|
/// R^2 mod p
let fp_r2 : U256 = {
  l0: 0xf32cfc5b538afa89UL,
  l1: 0xb5e71911d44501fbUL,
  l2: 0x47ab1eff0a417ff6UL,
  l3: 0x06d89f71cab8351fUL,
}

///|
/// -p^-1 mod 2^64
let fp_inv : UInt64 = 0x87d20782e4866389UL

///|
/// p - 2 (for Fermat inversion)
let fp_minus_2 : U256 = {
  l0: 0x3c208c16d87cfd45UL,
  l1: 0x97816a916871ca8dUL,
  l2: 0xb85045b68181585dUL,
  l3: 0x30644e72e131a029UL,
}

///|
/// (p + 1) / 4 (since p == 3 mod 4, used for square root)
let fp_plus_1_div_4 : U256 = {
  l0: 0x4f082305b61f3f52UL,
  l1: 0x65e05aa45a1c72a3UL,
  l2: 0x6e14116da0605617UL,
  l3: 0x0c19139cb84c680aUL,
}

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

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

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

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

///|
/// Construct from an already-Montgomery-encoded U256 (internal constant helper).
fn Fp::from_raw(v : U256) -> Fp {
  { v, }
}

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

///|
pub fn Fp::one() -> Fp {
  { v: fp_r, }
}

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

///|
/// Convert a canonical integer u < p into Fp. Raises InvalidFieldElement if u >= p.
pub fn Fp::from_u256(u : U256) -> Fp raise ZkError {
  if u.cmp(fp_modulus) >= 0 {
    raise ZkError::InvalidFieldElement("Fp element >= p: \{u.to_decimal()}")
  }
  { v: mont_mul(u, fp_r2, fp_modulus, fp_inv), }
}

///|
/// Construct Fp from a UInt64.
pub fn Fp::from_u64(x : UInt64) -> Fp {
  { v: mont_mul(U256::from_u64(x), fp_r2, fp_modulus, fp_inv), }
}

///|
/// Construct Fp from a signed Int (negative values are negated mod p).
pub fn Fp::from_int(x : Int32) -> Fp {
  if x >= 0 {
    Fp::from_u64(x.to_uint64())
  } else {
    Fp::from_u64((-x).to_uint64()).neg()
  }
}

///|
/// Convert back from Montgomery form to canonical U256 in [0, p-1].
pub fn Fp::to_u256(self : Fp) -> U256 {
  mont_mul(self.v, U256::one(), fp_modulus, fp_inv)
}

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

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

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

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

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

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

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

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

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

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

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

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

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

///|
pub fn Fp::mul(self : Fp, other : Fp) -> Fp {
  { v: mont_mul(self.v, other.v, fp_modulus, fp_inv), }
}

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

///|
pub fn Fp::pow(self : Fp, exp : U256) -> Fp {
  let mut res = Fp::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
}

///|
/// Multiplicative inverse in F_p. Returns None for 0.
pub fn Fp::inv(self : Fp) -> Fp? {
  if self.is_zero() {
    None
  } else {
    Some(self.pow(fp_minus_2))
  }
}

///|
/// Square root in F_p (returns Some(r) with r^2 == self if self is a quadratic residue).
pub fn Fp::sqrt(self : Fp) -> Fp? {
  let cand = self.pow(fp_plus_1_div_4)
  if cand.square() == self {
    Some(cand)
  } else {
    None
  }
}

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

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

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

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