///|
/// Return the smallest power of two >= n (minimum 1) along with its log2.
pub fn next_power_of_two(n : Int32) -> (Int32, Int32) {
  let mut p = 1
  let mut log_p = 0
  while p < n {
    p = p << 1
    log_p = log_p + 1
  }
  (p, log_p)
}

///|
/// In-place Radix-2 Cooley-Tukey NTT/FFT over F_r.
/// `a.length()` must be a power of 2 and `omega` a primitive n-th root of unity.
pub fn fft_in_place(a : Array[Fr], omega : Fr) -> Unit {
  let n = a.length()
  if n <= 1 {
    return
  }
  // Bit-reversal permutation
  let mut j = 0
  for i = 1; i < n; i = i + 1 {
    let mut bit = n >> 1
    while (j & bit) != 0 {
      j = j ^ bit
      bit = bit >> 1
    }
    j = j ^ bit
    if i < j {
      let tmp = a[i]
      a[i] = a[j]
      a[j] = tmp
    }
  }
  // Butterfly stages
  let mut len = 2
  while len <= n {
    let step = n / len
    let wlen = omega.pow(U256::from_u64(step.to_uint64()))
    let half = len >> 1
    let mut i = 0
    while i < n {
      let mut w = Fr::one()
      for k = 0; k < half; k = k + 1 {
        let u = a[i + k]
        let v = a[i + k + half].mul(w)
        a[i + k] = u.add(v)
        a[i + k + half] = u.sub(v)
        w = w.mul(wlen)
      }
      i = i + len
    }
    len = len << 1
  }
}

///|
/// In-place inverse Radix-2 NTT/FFT over F_r.
pub fn ifft_in_place(a : Array[Fr], omega : Fr) -> Unit raise ZkError {
  let n = a.length()
  if n <= 1 {
    return
  }
  let omega_inv = match omega.inv() {
    None => raise ZkError::InvalidInput("root of unity cannot be zero")
    Some(v) => v
  }
  let n_inv = match Fr::from_u64(n.to_uint64()).inv() {
    None => raise ZkError::InvalidInput("FFT size cannot be zero")
    Some(v) => v
  }
  fft_in_place(a, omega_inv)
  for i = 0; i < n; i = i + 1 {
    a[i] = a[i].mul(n_inv)
  }
}

///|
/// Evaluate polynomial coefficients on coset shift *  in-place.
pub fn coset_fft_in_place(a : Array[Fr], omega : Fr, shift : Fr) -> Unit {
  let mut p = Fr::one()
  for i = 0; i < a.length(); i = i + 1 {
    a[i] = a[i].mul(p)
    p = p.mul(shift)
  }
  fft_in_place(a, omega)
}

///|
/// Interpolate polynomial coefficients from evaluations on coset shift *  in-place.
pub fn coset_ifft_in_place(
  a : Array[Fr],
  omega : Fr,
  shift : Fr,
) -> Unit raise ZkError {
  ifft_in_place(a, omega)
  let shift_inv = match shift.inv() {
    None => raise ZkError::InvalidInput("coset shift cannot be zero")
    Some(v) => v
  }
  let mut p = Fr::one()
  for i = 0; i < a.length(); i = i + 1 {
    a[i] = a[i].mul(p)
    p = p.mul(shift_inv)
  }
}

///|
/// Compute the QAP quotient polynomial H(X) = (A(X)*B(X) - C(X)) / (X^n - 1)
/// in O(n log n) via Coset FFT. Returns n-1 coefficients [h_0, ..., h_{n-2}].
pub fn compute_qap_h(
  r1cs : R1cs,
  witness : Array[Fr],
) -> Array[Fr] raise ZkError {
  let m_con = r1cs.constraints.length()
  let (n, log_n) = next_power_of_two(if m_con < 1 { 1 } else { m_con })
  let omega = Fr::root_of_unity(log_n)
  let shift = Fr::multiplicative_generator()

  let a_poly : Array[Fr] = Array::make(n, Fr::zero())
  let b_poly : Array[Fr] = Array::make(n, Fr::zero())
  let c_poly : Array[Fr] = Array::make(n, Fr::zero())

  for i = 0; i < m_con; i = i + 1 {
    let con = r1cs.constraints[i]
    a_poly[i] = con.a.eval(witness)
    b_poly[i] = con.b.eval(witness)
    c_poly[i] = con.c.eval(witness)
  }

  // Interpolate A(X), B(X), C(X) from domain 
  ifft_in_place(a_poly, omega)
  ifft_in_place(b_poly, omega)
  ifft_in_place(c_poly, omega)

  // Evaluate on coset shift * 
  coset_fft_in_place(a_poly, omega, shift)
  coset_fft_in_place(b_poly, omega, shift)
  coset_fft_in_place(c_poly, omega, shift)

  // Z(shift * omega^i) = shift^n - 1 is constant across the entire coset
  let z_coset = shift.pow(U256::from_u64(n.to_uint64())).sub(Fr::one())
  let z_inv = match z_coset.inv() {
    None => raise ZkError::InvalidR1cs("coset vanishing polynomial is zero")
    Some(v) => v
  }
  for i = 0; i < n; i = i + 1 {
    a_poly[i] = a_poly[i].mul(b_poly[i]).sub(c_poly[i]).mul(z_inv)
  }

  // Interpolate H(X) from coset evaluations
  coset_ifft_in_place(a_poly, omega, shift)
  if n <= 1 {
    return []
  }
  let h : Array[Fr] = Array::make(n - 1, Fr::zero())
  for i = 0; i < n - 1; i = i + 1 {
    h[i] = a_poly[i]
  }
  h
}