///|
/// BN254 curve parameter x = 4965661367192848881 = 0x44e992b44a6909f1.
let bn_x : UInt64 = 0x44e992b44a6909f1UL

///|
/// Non-Adjacent Form (NAF) of 6x + 2 = 29793968203157093288, MSB to LSB excluding the leading 1.
let ate_loop_naf : FixedArray[Int32] = [
  0, -1, 0, 1, 0, 0, 0, -1, 0, -1, 0, 0, 0, -1, 0, 1, 0, -1, 0, 0, -1, 0, 0, 0, 0,
  0, 1, 0, 0, -1, 0, 1, 0, 0, -1, 0, 0, 0, 0, -1, 0, 1, 0, 0, 0, -1, 0, -1, 0, 0,
  1, 0, 0, 0, -1, 0, 0, -1, 0, 1, 0, 1, 0, 0, 0,
]

///|
/// Homogeneous projective G2 point used internally inside the Miller loop.
priv struct G2Homog {
  mut x : Fq2
  mut y : Fq2
  mut z : Fq2
}

///|
/// Line coefficients (c0, c3, c4) evaluated at P for sparse Fq12::mul_by_034.
priv struct LineCoeff {
  c0 : Fq2
  c3 : Fq2
  c4 : Fq2
}

///|
/// Constant 2^-1 in F_p, used in homogeneous doubling.
let fp_inv_2 : Fp = Fp::from_u64(2UL).inv().unwrap()

///|
/// Doubling step in homogeneous coordinates on E': Y^2 Z = X^3 + b' Z^3.
/// Updates T <- 2*T and returns sparse line coefficients (c0, c3, c4) evaluated at P.
fn miller_double_step(t : G2Homog, p : G1Affine) -> LineCoeff {
  let a = t.x.mul(t.y).mul_fp(fp_inv_2)
  let b = t.y.square()
  let c = t.z.square()
  let d = c.double().add(c) // 3*Z^2
  let e = g2_b.mul(d) // 3*b'*Z^2
  let f = e.double().add(e) // 9*b'*Z^2
  let g = b.add(f).mul_fp(fp_inv_2)
  let h = t.y.add(t.z).square().sub(b).sub(c) // 2*Y*Z
  let i = e.sub(b) // 3*b'*Z^2 - Y^2
  let j = t.x.square()
  let e2 = e.square()

  let new_x = a.mul(b.sub(f))
  let new_y = g.square().sub(e2.double().add(e2))
  let new_z = b.mul(h)

  t.x = new_x
  t.y = new_y
  t.z = new_z

  let j3 = j.double().add(j)
  { c0: h.neg().mul_fp(p.y), c3: j3.mul_fp(p.x), c4: i, }
}

///|
/// Addition step in homogeneous coordinates: T <- T + Q (affine),
/// returning sparse line coefficients (c0, c3, c4) evaluated at P.
fn miller_add_step(t : G2Homog, q : G2Affine, p : G1Affine) -> LineCoeff {
  let theta = t.y.sub(q.y.mul(t.z))
  let lambda = t.x.sub(q.x.mul(t.z))
  let c = theta.square()
  let d = lambda.square()
  let e = lambda.mul(d)
  let f = t.z.mul(c)
  let g = t.x.mul(d)
  let h = e.add(f).sub(g.double())

  let new_x = lambda.mul(h)
  let new_y = theta.mul(g.sub(h)).sub(e.mul(t.y))
  let new_z = t.z.mul(e)

  t.x = new_x
  t.y = new_y
  t.z = new_z

  let c4 = theta.mul(q.x).sub(lambda.mul(q.y))
  { c0: lambda.mul_fp(p.y), c3: theta.neg().mul_fp(p.x), c4, }
}

///|
/// Multi-pair Miller loop over non-identity pairs (P_i, Q_i).
pub fn miller_loop(pairs : Array[(G1Affine, G2Affine)]) -> Fq12 {
  let active_p : Array[G1Affine] = []
  let active_q : Array[G2Affine] = []
  let active_neg_q : Array[G2Affine] = []
  let active_t : Array[G2Homog] = []

  for pair in pairs {
    let (p, q) = pair
    if !p.infinity && !q.infinity {
      active_p.push(p)
      active_q.push(q)
      active_neg_q.push(q.neg())
      active_t.push({ x: q.x, y: q.y, z: Fq2::one(), })
    }
  }
  let m = active_p.length()
  if m == 0 {
    return Fq12::one()
  }

  let mut f = Fq12::one()
  for bit in ate_loop_naf {
    f = f.square()
    for i = 0; i < m; i = i + 1 {
      let l = miller_double_step(active_t[i], active_p[i])
      f = f.mul_by_034(l.c0, l.c3, l.c4)
      if bit == 1 {
        let la = miller_add_step(active_t[i], active_q[i], active_p[i])
        f = f.mul_by_034(la.c0, la.c3, la.c4)
      } else if bit == -1 {
        let la = miller_add_step(active_t[i], active_neg_q[i], active_p[i])
        f = f.mul_by_034(la.c0, la.c3, la.c4)
      }
    }
  }

  // BN254 Frobenius correction steps: add Q1 = pi(Q) and -Q2 = -pi^2(Q)
  for i = 0; i < m; i = i + 1 {
    let q1 = active_q[i].frobenius_map_1()
    let l1 = miller_add_step(active_t[i], q1, active_p[i])
    f = f.mul_by_034(l1.c0, l1.c3, l1.c4)

    let neg_q2 = active_q[i].frobenius_map_2().neg()
    let l2 = miller_add_step(active_t[i], neg_q2, active_p[i])
    f = f.mul_by_034(l2.c0, l2.c3, l2.c4)
  }
  f
}

///|
/// Helper: raise a cyclotomic Fq12 element to the 6th power (2 squarings + 1 mul).
fn cyc_pow6(a : Fq12) -> Fq12 {
  let a2 = a.cyclotomic_square()
  let a4 = a2.cyclotomic_square()
  a4.mul(a2)
}

///|
/// Exact BN254 Final Exponentiation: f^((p^12 - 1) / r).
/// Easy part: f^((p^6 - 1)(p^2 + 1)).
/// Hard part: f^((p^4 - p^2 + 1) / r) via Devegili base-p decomposition.
pub fn final_exponentiation(f : Fq12) -> Fq12 {
  // Easy part
  let f_inv = match f.inv() {
    None => return Fq12::one()
    Some(v) => v
  }
  let f1 = f.conjugate().mul(f_inv) // f^(p^6 - 1)
  let f2 = f1.frobenius_map(2).mul(f1) // f^((p^6 - 1)(p^2 + 1))

  // Hard part: lambda_3 = 1, lambda_2 = 6x^2 + 1,
  // lambda_1 = -36x^3 - 18x^2 - 12x + 1, lambda_0 = -36x^3 - 30x^2 - 18x - 2
  let fx = f2.cyclotomic_pow_u64(bn_x)
  let fx2 = fx.cyclotomic_pow_u64(bn_x)
  let fx3 = fx2.cyclotomic_pow_u64(bn_x)

  let f6x = cyc_pow6(fx)
  let f6x2 = cyc_pow6(fx2)
  let f6x3 = cyc_pow6(fx3)

  let f12x = f6x.cyclotomic_square()
  let f18x = f12x.mul(f6x)

  let f12x2 = f6x2.cyclotomic_square()
  let f18x2 = f12x2.mul(f6x2)
  let f30x2 = f18x2.mul(f12x2)

  let f36x3 = cyc_pow6(f6x3)

  let y0 = f36x3.mul(f30x2).mul(f18x).mul(f2.cyclotomic_square()).conjugate()
  let y1 = f36x3.mul(f18x2).mul(f12x).conjugate().mul(f2)
  let y2 = f6x2.mul(f2)
  let y3 = f2

  y0.mul(y1.frobenius_map(1)).mul(y2.frobenius_map(2)).mul(y3.frobenius_map(3))
}

///|
/// Compute the Optimal Ate pairing e(P, Q) in GT subset F_{p^12}*.
pub fn pairing(p : G1Affine, q : G2Affine) -> Fq12 {
  if p.infinity || q.infinity {
    return Fq12::one()
  }
  final_exponentiation(miller_loop([(p, q)]))
}

///|
/// Compute the product of pairings prod_i e(P_i, Q_i) with a single shared final exponentiation.
pub fn multi_pairing(pairs : Array[(G1Affine, G2Affine)]) -> Fq12 {
  final_exponentiation(miller_loop(pairs))
}

///|
/// Check whether prod_i e(P_i, Q_i) == 1 in GT.
pub fn multi_pairing_check(pairs : Array[(G1Affine, G2Affine)]) -> Bool {
  multi_pairing(pairs).is_one()
}

///|
/// Ethereum EIP-196 `ecAdd` precompile (address 0x06):
/// Input: 128 bytes (zero-padded or truncated per EVM semantics) = G1 || G1.
/// Output: 64 bytes = G1.
pub fn eip196_ecadd(input : BytesView) -> Bytes raise ZkError {
  let buf : FixedArray[Byte] = FixedArray::make(128, b'\x00')
  let copy_len = if input.length() < 128 { input.length() } else { 128 }
  for i = 0; i < copy_len; i = i + 1 {
    buf[i] = input[i]
  }
  let padded = Bytes::from_array(buf)
  let p1 = G1Affine::from_eip196_bytes(padded[0:64])
  let p2 = G1Affine::from_eip196_bytes(padded[64:128])
  p1.to_projective().add_mixed(p2).to_affine().to_eip196_bytes()
}

///|
/// Ethereum EIP-196 `ecMul` precompile (address 0x07):
/// Input: 96 bytes (zero-padded or truncated) = G1 (64B) || scalar (32B big-endian, arbitrary U256).
/// Output: 64 bytes = G1.
pub fn eip196_ecmul(input : BytesView) -> Bytes raise ZkError {
  let buf : FixedArray[Byte] = FixedArray::make(96, b'\x00')
  let copy_len = if input.length() < 96 { input.length() } else { 96 }
  for i = 0; i < copy_len; i = i + 1 {
    buf[i] = input[i]
  }
  let padded = Bytes::from_array(buf)
  let p = G1Affine::from_eip196_bytes(padded[0:64])
  let s = U256::from_be_bytes(padded[64:96])
  p.to_projective().scalar_mul_u256(s).to_affine().to_eip196_bytes()
}

///|
/// Encode a list of (G1, G2) pairs into Ethereum EIP-197 precompile input bytes (192 bytes per pair).
pub fn eip197_encode_pairs(pairs : Array[(G1Affine, G2Affine)]) -> Bytes {
  let buf = Buffer(size_hint=pairs.length() * 192)
  for pair in pairs {
    let (p, q) = pair
    buf.write_bytesview(p.to_eip196_bytes()[:])
    buf.write_bytesview(q.to_eip197_bytes()[:])
  }
  buf.to_bytes()
}

///|
/// Ethereum EIP-197 `ecPairing` precompile (address 0x08):
/// Input: 192*k bytes = k pairs of (G1 (64B) || G2 (128B)).
/// Returns true iff prod_i e(P_i, Q_i) == 1. Rejects non-multiple-of-192 lengths,
/// non-canonical coordinates, off-curve points, and non-subgroup G2 points.
pub fn eip197_ecpairing(input : BytesView) -> Bool raise ZkError {
  if input.length() % 192 != 0 {
    raise ZkError::InvalidInput(
      "EIP-197 input length must be a multiple of 192 bytes, got \{input.length()}",
    )
  }
  let k = input.length() / 192
  let pairs : Array[(G1Affine, G2Affine)] = []
  for i = 0; i < k; i = i + 1 {
    let off = i * 192
    let p = G1Affine::from_eip196_bytes(input[off:off + 64])
    let q = G2Affine::from_eip197_bytes(input[off + 64:off + 192])
    pairs.push((p, q))
  }
  multi_pairing_check(pairs)
}