///|
/// Curve constant b = 3 for BN254 G1: y^2 = x^3 + 3 over F_p.
let g1_b : Fp = Fp::from_u64(3UL)

///|
/// Affine point on BN254 G1 (y^2 = x^3 + 3 over F_p).
#derive(Debug, Eq, Hash)
pub struct G1Affine {
  x : Fp
  y : Fp
  infinity : Bool
}

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

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

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

///|
/// Jacobian projective point on BN254 G1 (represents affine (x/z^2, y/z^3), infinity when z == 0).
#derive(Debug, Eq, Hash)
pub struct G1Projective {
  x : Fp
  y : Fp
  z : Fp
}

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

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

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

///|
pub fn G1Affine::identity() -> G1Affine {
  { x: Fp::zero(), y: Fp::zero(), infinity: true, }
}

///|
/// Standard BN254 G1 generator (1, 2).
pub fn G1Affine::generator() -> G1Affine {
  { x: Fp::one(), y: Fp::from_u64(2UL), infinity: false, }
}

///|
pub fn G1Affine::is_identity(self : G1Affine) -> Bool {
  self.infinity
}

///|
/// Verify whether the point lies on y^2 = x^3 + 3 (identity is always on curve).
pub fn G1Affine::is_on_curve(self : G1Affine) -> Bool {
  if self.infinity {
    return true
  }
  self.y.square() == self.x.square().mul(self.x).add(g1_b)
}

///|
/// Construct a checked G1Affine point from (x, y).
/// Note: (0, 0) is rejected here; use `G1Affine::identity()` or `from_eip196_bytes` for infinity.
pub fn G1Affine::from_xy(x : Fp, y : Fp) -> G1Affine raise ZkError {
  let pt : G1Affine = { x, y, infinity: false, }
  if !pt.is_on_curve() {
    raise ZkError::InvalidCurvePoint(
      "G1 point not on curve y^2 = x^3 + 3: (\{x}, \{y})",
    )
  }
  pt
}

///|
/// Construct from coordinates where (0, 0) represents the point at infinity (EIP-196 convention).
pub fn G1Affine::from_xy_or_zero(x : Fp, y : Fp) -> G1Affine raise ZkError {
  if x.is_zero() && y.is_zero() {
    return G1Affine::identity()
  }
  G1Affine::from_xy(x, y)
}

///|
/// Negate a G1Affine point.
pub fn G1Affine::neg(self : G1Affine) -> G1Affine {
  if self.infinity {
    self
  } else {
    { x: self.x, y: self.y.neg(), infinity: false, }
  }
}

///|
pub fn G1Affine::to_projective(self : G1Affine) -> G1Projective {
  if self.infinity {
    G1Projective::identity()
  } else {
    { x: self.x, y: self.y, z: Fp::one(), }
  }
}

///|
/// Encode G1Affine as 64-byte big-endian Ethereum EIP-196/197 format (all zeros for infinity).
pub fn G1Affine::to_eip196_bytes(self : G1Affine) -> Bytes {
  let out : FixedArray[Byte] = FixedArray::make(64, b'\x00')
  if self.infinity {
    return Bytes::from_array(out)
  }
  let xb = self.x.to_be_bytes()
  let yb = self.y.to_be_bytes()
  for i = 0; i < 32; i = i + 1 {
    out[i] = xb[i]
    out[32 + i] = yb[i]
  }
  Bytes::from_array(out)
}

///|
/// Decode G1Affine from 64-byte big-endian Ethereum EIP-196/197 format.
/// Enforces canonical F_p (< p) and curve membership (all-zero = identity).
pub fn G1Affine::from_eip196_bytes(bytes : BytesView) -> G1Affine raise ZkError {
  if bytes.length() != 64 {
    raise ZkError::InvalidCurvePoint(
      "expected 64 bytes for G1 point, got \{bytes.length()}",
    )
  }
  let x = Fp::from_be_bytes(bytes[0:32])
  let y = Fp::from_be_bytes(bytes[32:64])
  G1Affine::from_xy_or_zero(x, y)
}

///|
pub fn G1Projective::identity() -> G1Projective {
  { x: Fp::zero(), y: Fp::one(), z: Fp::zero(), }
}

///|
pub fn G1Projective::generator() -> G1Projective {
  G1Affine::generator().to_projective()
}

///|
pub fn G1Projective::is_identity(self : G1Projective) -> Bool {
  self.z.is_zero()
}

///|
pub fn G1Projective::neg(self : G1Projective) -> G1Projective {
  if self.is_identity() {
    self
  } else {
    { x: self.x, y: self.y.neg(), z: self.z, }
  }
}

///|
/// Convert Jacobian projective point to canonical affine coordinates.
pub fn G1Projective::to_affine(self : G1Projective) -> G1Affine {
  match self.z.inv() {
    None => G1Affine::identity()
    Some(z_inv) => {
      let z_inv2 = z_inv.square()
      let z_inv3 = z_inv2.mul(z_inv)
      { x: self.x.mul(z_inv2), y: self.y.mul(z_inv3), infinity: false, }
    }
  }
}

///|
/// Jacobian doubling for a = 0 curve (dbl-2009-l).
pub fn G1Projective::double(self : G1Projective) -> G1Projective {
  if self.is_identity() || self.y.is_zero() {
    return G1Projective::identity()
  }
  let a = self.x.square()
  let b = self.y.square()
  let c = b.square()
  let d = self.x.add(b).square().sub(a).sub(c).double()
  let e = a.double().add(a)
  let f = e.square()
  let x3 = f.sub(d.double())
  let c8 = c.double().double().double()
  let y3 = e.mul(d.sub(x3)).sub(c8)
  let z3 = self.y.mul(self.z).double()
  { x: x3, y: y3, z: z3, }
}

///|
/// Mixed addition: Jacobian + Affine (madd-2007-bl).
pub fn G1Projective::add_mixed(
  self : G1Projective,
  other : G1Affine,
) -> G1Projective {
  if other.infinity {
    return self
  }
  if self.is_identity() {
    return other.to_projective()
  }
  let z1z1 = self.z.square()
  let u2 = other.x.mul(z1z1)
  let s2 = other.y.mul(self.z).mul(z1z1)
  if self.x == u2 {
    if self.y == s2 {
      return self.double()
    } else {
      return G1Projective::identity()
    }
  }
  let h = u2.sub(self.x)
  let hh = h.square()
  let i = hh.double().double()
  let j = h.mul(i)
  let r = s2.sub(self.y).double()
  let v = self.x.mul(i)
  let x3 = r.square().sub(j).sub(v.double())
  let y3 = r.mul(v.sub(x3)).sub(self.y.mul(j).double())
  let z3 = self.z.add(h).square().sub(z1z1).sub(hh)
  { x: x3, y: y3, z: z3, }
}

///|
/// General Jacobian addition (add-2007-bl).
pub fn G1Projective::add(
  self : G1Projective,
  other : G1Projective,
) -> G1Projective {
  if self.is_identity() {
    return other
  }
  if other.is_identity() {
    return self
  }
  let z1z1 = self.z.square()
  let z2z2 = other.z.square()
  let u1 = self.x.mul(z2z2)
  let u2 = other.x.mul(z1z1)
  let s1 = self.y.mul(other.z).mul(z2z2)
  let s2 = other.y.mul(self.z).mul(z1z1)
  if u1 == u2 {
    if s1 == s2 {
      return self.double()
    } else {
      return G1Projective::identity()
    }
  }
  let h = u2.sub(u1)
  let i = h.double().square()
  let j = h.mul(i)
  let r = s2.sub(s1).double()
  let v = u1.mul(i)
  let x3 = r.square().sub(j).sub(v.double())
  let y3 = r.mul(v.sub(x3)).sub(s1.mul(j).double())
  let z3 = self.z.add(other.z).square().sub(z1z1).sub(z2z2).mul(h)
  { x: x3, y: y3, z: z3, }
}

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

///|
/// Scalar multiplication [s]P using 4-bit fixed window.
pub fn G1Projective::scalar_mul_u256(
  self : G1Projective,
  s : U256,
) -> G1Projective {
  if self.is_identity() || s.is_zero() {
    return G1Projective::identity()
  }
  let table : FixedArray[G1Projective] = FixedArray::make(
    16,
    G1Projective::identity(),
  )
  table[1] = self
  for i = 2; i < 16; i = i + 1 {
    table[i] = table[i - 1].add(self)
  }
  let mut acc = G1Projective::identity()
  let limbs : FixedArray[UInt64] = [s.l3, s.l2, s.l1, s.l0]
  let mut started = false
  for li = 0; li < 4; li = li + 1 {
    let v = limbs[li]
    for sh = 60; sh >= 0; sh = sh - 4 {
      if started {
        acc = acc.double().double().double().double()
      }
      let w = ((v >> sh) & 0xfUL).to_int()
      if w != 0 {
        acc = if started { acc.add(table[w]) } else { table[w] }
        started = true
      }
    }
  }
  acc
}

///|
pub fn G1Projective::scalar_mul(self : G1Projective, s : Fr) -> G1Projective {
  self.scalar_mul_u256(s.to_u256())
}

///|
pub fn G1Affine::scalar_mul(self : G1Affine, s : Fr) -> G1Projective {
  self.to_projective().scalar_mul(s)
}

///|
/// Pippenger multi-scalar multiplication: computes sum_i [scalars[i]] * bases[i].
pub fn g1_msm(
  bases : Array[G1Affine],
  scalars : Array[Fr],
) -> G1Projective raise ZkError {
  if bases.length() != scalars.length() {
    raise ZkError::InvalidInput(
      "g1_msm length mismatch: \{bases.length()} bases vs \{scalars.length()} scalars",
    )
  }
  let n = bases.length()
  if n == 0 {
    return G1Projective::identity()
  }
  if n < 8 {
    let mut acc = G1Projective::identity()
    for i = 0; i < n; i = i + 1 {
      if !bases[i].infinity && !scalars[i].is_zero() {
        acc = acc.add(bases[i].scalar_mul(scalars[i]))
      }
    }
    return acc
  }
  // Choose bucket window width c based on n
  let c = if n < 32 {
    4
  } else if n < 256 {
    6
  } else if n < 2048 {
    8
  } else {
    10
  }
  let num_buckets = (1 << c) - 1
  let mask : UInt64 = ((1 << c) - 1).to_uint64()
  let num_windows = (254 + c - 1) / c

  let raw_scalars : Array[U256] = Array::make(n, U256::zero())
  for i = 0; i < n; i = i + 1 {
    raw_scalars[i] = scalars[i].to_u256()
  }

  let mut total = G1Projective::identity()
  for w = num_windows - 1; w >= 0; w = w - 1 {
    for _k = 0; _k < c; _k = _k + 1 {
      total = total.double()
    }
    let buckets : FixedArray[G1Projective] = FixedArray::make(
      num_buckets,
      G1Projective::identity(),
    )
    let bit_offset = w * c
    for i = 0; i < n; i = i + 1 {
      if bases[i].infinity {
        continue
      }
      let sc = raw_scalars[i]
      if sc.is_zero() {
        continue
      }
      // Extract c bits starting at bit_offset
      let limb_idx = bit_offset / 64
      let intra = bit_offset % 64
      let lo_limb = match limb_idx {
        0 => sc.l0
        1 => sc.l1
        2 => sc.l2
        _ => sc.l3
      }
      let mut bits = lo_limb >> intra
      if intra + c > 64 && limb_idx < 3 {
        let hi_limb = match limb_idx + 1 {
          1 => sc.l1
          2 => sc.l2
          _ => sc.l3
        }
        bits = bits | (hi_limb << (64 - intra))
      }
      let bucket_idx = (bits & mask).to_int()
      if bucket_idx != 0 {
        buckets[bucket_idx - 1] = buckets[bucket_idx - 1].add_mixed(bases[i])
      }
    }
    let mut running = G1Projective::identity()
    let mut window_sum = G1Projective::identity()
    for b = num_buckets - 1; b >= 0; b = b - 1 {
      if !buckets[b].is_identity() {
        running = running.add(buckets[b])
      }
      if !running.is_identity() {
        window_sum = window_sum.add(running)
      }
    }
    total = total.add(window_sum)
  }
  total
}

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

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

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