///|
/// Twist curve constant b' = 3 / (9 + u) for BN254 G2: y^2 = x^3 + b' over F_{p^2}.
pub let g2_b : Fq2 = {
  c0: Fp::from_raw(
    U256::new(
      0x3bf938e377b802a8UL, 0x020b1b273633535dUL, 0x26b7edf049755260UL, 0x2514c6324384a86dUL,
    ),
  ),
  c1: Fp::from_raw(
    U256::new(
      0x38e7ecccd1dcff67UL, 0x65f0b37d93ce0d3eUL, 0xd749d0dd22ac00aaUL, 0x0141b9ce4a688d4dUL,
    ),
  ),
}

///|
/// G2 Frobenius endomorphism constants:
/// psi(x, y) = (x^p * xi^((p-1)/3), y^p * xi^((p-1)/2))
let g2_frob1_x : Fq2 = {
  c0: Fp::from_raw(
    U256::new(
      0xb5773b104563ab30UL, 0x347f91c8a9aa6454UL, 0x7a007127242e0991UL, 0x1956bcd8118214ecUL,
    ),
  ),
  c1: Fp::from_raw(
    U256::new(
      0x6e849f1ea0aa4757UL, 0xaa1c7b6d89f89141UL, 0xb6e713cdfae0ca3aUL, 0x26694fbb4e82ebc3UL,
    ),
  ),
}

///|
let g2_frob1_y : Fq2 = {
  c0: Fp::from_raw(
    U256::new(
      0xe4bbdd0c2936b629UL, 0xbb30f162e133bacbUL, 0x31a9d1b6f9645366UL, 0x253570bea500f8ddUL,
    ),
  ),
  c1: Fp::from_raw(
    U256::new(
      0xa1d77ce45ffe77c7UL, 0x07affd117826d1dbUL, 0x6d16bd27bb7edc6bUL, 0x2c87200285defeccUL,
    ),
  ),
}

///|
let g2_frob2_x : Fp = Fp::from_raw(
  U256::new(
    0x3350c88e13e80b9cUL, 0x7dce557cdb5e56b9UL, 0x6001b4b8b615564aUL, 0x2682e617020217e0UL,
  ),
)

///|
let g2_frob2_y : Fp = Fp::from_raw(
  U256::new(
    0x68c3488912edefaaUL, 0x8d087f6872aabf4fUL, 0x51e1a24709081231UL, 0x2259d6b14729c0faUL,
  ),
)

///|
/// Affine point on BN254 G2 (y^2 = x^3 + 3/(9+u) over F_{p^2}).
#derive(Debug, Eq, Hash)
pub struct G2Affine {
  x : Fq2
  y : Fq2
  infinity : Bool
}

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

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

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

///|
/// Jacobian projective point on BN254 G2.
#derive(Debug, Eq, Hash)
pub struct G2Projective {
  x : Fq2
  y : Fq2
  z : Fq2
}

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

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

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

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

///|
/// Standard BN254 G2 generator (EIP-197 / snarkjs / arkworks).
pub fn G2Affine::generator() -> G2Affine {
  let x_c0 = try! Fp::from_decimal(
    "10857046999023057135944570762232829481370756359578518086990519993285655852781",
  )
  let x_c1 = try! Fp::from_decimal(
    "11559732032986387107991004021392285783925812861821192530917403151452391805634",
  )
  let y_c0 = try! Fp::from_decimal(
    "8495653923123431417604973247489272438418190587263600148770280649306958101930",
  )
  let y_c1 = try! Fp::from_decimal(
    "4082367875863433681332203403145435568316851327593401208105741076214120093531",
  )
  { x: Fq2::new(x_c0, x_c1), y: Fq2::new(y_c0, y_c1), infinity: false, }
}

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

///|
/// Verify whether the point lies on the twist curve y^2 = x^3 + 3/(9+u).
pub fn G2Affine::is_on_curve(self : G2Affine) -> Bool {
  if self.infinity {
    return true
  }
  self.y.square() == self.x.square().mul(self.x).add(g2_b)
}

///|
/// Strict prime-order r subgroup check: verifies curve membership AND [r]Q == O.
/// Rejects invalid-curve and small-subgroup attacks (required by EIP-197).
pub fn G2Affine::is_in_subgroup(self : G2Affine) -> Bool {
  if self.infinity {
    return true
  }
  if !self.is_on_curve() {
    return false
  }
  self.to_projective().scalar_mul_u256(fr_modulus).is_identity()
}

///|
/// Construct a checked G2Affine point on the twist curve and in the prime-order subgroup G2.
pub fn G2Affine::from_xy(x : Fq2, y : Fq2) -> G2Affine raise ZkError {
  let pt : G2Affine = { x, y, infinity: false, }
  if !pt.is_on_curve() {
    raise ZkError::InvalidCurvePoint("G2 point not on twist curve")
  }
  if !pt.is_in_subgroup() {
    raise ZkError::InvalidSubgroup("G2 point not in prime-order subgroup")
  }
  pt
}

///|
/// Construct from coordinates where (0, 0) represents the identity (EIP-197 convention).
pub fn G2Affine::from_xy_or_zero(x : Fq2, y : Fq2) -> G2Affine raise ZkError {
  if x.is_zero() && y.is_zero() {
    return G2Affine::identity()
  }
  G2Affine::from_xy(x, y)
}

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

///|
/// Frobenius endomorphism pi(Q) on G2: (x^p * xi^((p-1)/3), y^p * xi^((p-1)/2)).
pub fn G2Affine::frobenius_map_1(self : G2Affine) -> G2Affine {
  if self.infinity {
    self
  } else {
    {
      x: self.x.conjugate().mul(g2_frob1_x),
      y: self.y.conjugate().mul(g2_frob1_y),
      infinity: false,
    }
  }
}

///|
/// Double Frobenius endomorphism pi^2(Q) on G2.
pub fn G2Affine::frobenius_map_2(self : G2Affine) -> G2Affine {
  if self.infinity {
    self
  } else {
    {
      x: self.x.mul_fp(g2_frob2_x),
      y: self.y.mul_fp(g2_frob2_y),
      infinity: false,
    }
  }
}

///|
pub fn G2Affine::to_projective(self : G2Affine) -> G2Projective {
  if self.infinity {
    G2Projective::identity()
  } else {
    { x: self.x, y: self.y, z: Fq2::one(), }
  }
}

///|
/// Encode G2Affine in 128-byte Ethereum EIP-197 wire format: x.c1 || x.c0 || y.c1 || y.c0.
pub fn G2Affine::to_eip197_bytes(self : G2Affine) -> Bytes {
  let out : FixedArray[Byte] = FixedArray::make(128, b'\x00')
  if self.infinity {
    return Bytes::from_array(out)
  }
  let x1 = self.x.c1.to_be_bytes()
  let x0 = self.x.c0.to_be_bytes()
  let y1 = self.y.c1.to_be_bytes()
  let y0 = self.y.c0.to_be_bytes()
  for i = 0; i < 32; i = i + 1 {
    out[i] = x1[i]
    out[32 + i] = x0[i]
    out[64 + i] = y1[i]
    out[96 + i] = y0[i]
  }
  Bytes::from_array(out)
}

///|
/// Decode G2Affine from 128-byte Ethereum EIP-197 format (x.c1 || x.c0 || y.c1 || y.c0).
/// Strictly enforces canonical F_p (< p), curve membership, and prime-order subgroup membership.
pub fn G2Affine::from_eip197_bytes(bytes : BytesView) -> G2Affine raise ZkError {
  if bytes.length() != 128 {
    raise ZkError::InvalidCurvePoint(
      "expected 128 bytes for G2 point, got \{bytes.length()}",
    )
  }
  let x_c1 = Fp::from_be_bytes(bytes[0:32])
  let x_c0 = Fp::from_be_bytes(bytes[32:64])
  let y_c1 = Fp::from_be_bytes(bytes[64:96])
  let y_c0 = Fp::from_be_bytes(bytes[96:128])
  G2Affine::from_xy_or_zero(Fq2::new(x_c0, x_c1), Fq2::new(y_c0, y_c1))
}

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

///|
pub fn G2Projective::generator() -> G2Projective {
  G2Affine::generator().to_projective()
}

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

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

///|
pub fn G2Projective::to_affine(self : G2Projective) -> G2Affine {
  match self.z.inv() {
    None => G2Affine::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, }
    }
  }
}

///|
pub fn G2Projective::double(self : G2Projective) -> G2Projective {
  if self.is_identity() || self.y.is_zero() {
    return G2Projective::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, }
}

///|
pub fn G2Projective::add_mixed(
  self : G2Projective,
  other : G2Affine,
) -> G2Projective {
  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 G2Projective::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, }
}

///|
pub fn G2Projective::add(
  self : G2Projective,
  other : G2Projective,
) -> G2Projective {
  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 G2Projective::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 G2Projective::sub(
  self : G2Projective,
  other : G2Projective,
) -> G2Projective {
  self.add(other.neg())
}

///|
pub fn G2Projective::scalar_mul_u256(
  self : G2Projective,
  s : U256,
) -> G2Projective {
  if self.is_identity() || s.is_zero() {
    return G2Projective::identity()
  }
  let table : FixedArray[G2Projective] = FixedArray::make(
    16,
    G2Projective::identity(),
  )
  table[1] = self
  for i = 2; i < 16; i = i + 1 {
    table[i] = table[i - 1].add(self)
  }
  let mut acc = G2Projective::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 G2Projective::scalar_mul(self : G2Projective, s : Fr) -> G2Projective {
  self.scalar_mul_u256(s.to_u256())
}

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

///|
/// Pippenger multi-scalar multiplication over G2.
pub fn g2_msm(
  bases : Array[G2Affine],
  scalars : Array[Fr],
) -> G2Projective raise ZkError {
  if bases.length() != scalars.length() {
    raise ZkError::InvalidInput(
      "g2_msm length mismatch: \{bases.length()} bases vs \{scalars.length()} scalars",
    )
  }
  let n = bases.length()
  if n == 0 {
    return G2Projective::identity()
  }
  if n < 8 {
    let mut acc = G2Projective::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
  }
  let c = if n < 32 { 4 } else if n < 256 { 6 } else { 8 }
  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 = G2Projective::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[G2Projective] = FixedArray::make(
      num_buckets,
      G2Projective::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
      }
      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 = G2Projective::identity()
    let mut window_sum = G2Projective::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 G2Projective with fn add(self, other) {
  self.add(other)
}

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

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