///|
/// BN254 Poseidon ZK-Friendly Sponge Hash (t = 3, R_F = 8, R_P = 57, alpha = 5)
/// following the official Poseidon specification (Grassi et al., USENIX Security 2021)
/// with deterministic Grain-LFSR round constants and invertible Cauchy MDS matrix,
/// plus composable R1CS gadget and arbitrary-depth Poseidon Merkle membership circuits.
let poseidon_t : Int32 = 3

///|
let poseidon_rf : Int32 = 8

///|
let poseidon_rp : Int32 = 57

///|
let poseidon_rounds : Int32 = 65

///|
/// Official Poseidon Grain LFSR (80-bit state) generating canonical BN254 F_r round constants.
priv struct GrainLfsr {
  state : FixedArray[Bool]
}

///|
fn GrainLfsr::new(
  field : Int32,
  sbox : Int32,
  bits : Int32,
  t : Int32,
  rf : Int32,
  rp : Int32,
) -> GrainLfsr {
  let st : FixedArray[Bool] = FixedArray::make(80, true)
  fn set_bits(start : Int32, count : Int32, val : Int32) -> Unit {
    for i = 0; i < count; i = i + 1 {
      let shift = count - 1 - i
      st[start + i] = ((val >> shift) & 1) != 0
    }
  }
  set_bits(0, 2, field)
  set_bits(2, 4, sbox)
  set_bits(6, 12, bits)
  set_bits(18, 12, t)
  set_bits(30, 10, rf)
  set_bits(40, 10, rp)
  let g : GrainLfsr = { state: st, }
  // Discard first 160 bits per Poseidon spec §C.1
  for _i = 0; _i < 160; _i = _i + 1 {
    ignore(g.next_raw_bit())
  }
  g
}

///|
fn GrainLfsr::next_raw_bit(self : GrainLfsr) -> Bool {
  let b = self.state[62] !=
    (
      self.state[51] !=
      (self.state[38] != (self.state[23] != (self.state[13] != self.state[0])))
    )
  for i = 0; i < 79; i = i + 1 {
    self.state[i] = self.state[i + 1]
  }
  self.state[79] = b
  b
}

///|
fn GrainLfsr::next_bit(self : GrainLfsr) -> Bool {
  while true {
    let b0 = self.next_raw_bit()
    let b1 = self.next_raw_bit()
    if b0 {
      return b1
    }
  }
  false
}

///|
fn GrainLfsr::next_fr(self : GrainLfsr) -> Fr {
  while true {
    let mut l0 = 0UL
    let mut l1 = 0UL
    let mut l2 = 0UL
    let mut l3 = 0UL
    for i = 0; i < 254; i = i + 1 {
      let bit = if self.next_bit() { 1UL } else { 0UL }
      // Big-endian bit stream into 254-bit integer
      let pos = 253 - i
      let limb = pos / 64
      let sh = pos % 64
      match limb {
        0 => l0 = l0 | (bit << sh)
        1 => l1 = l1 | (bit << sh)
        2 => l2 = l2 | (bit << sh)
        _ => l3 = l3 | (bit << sh)
      }
    }
    let u = U256::new(l0, l1, l2, l3)
    if u.cmp(fr_modulus) < 0 {
      return Fr::from_u256_mod(u)
    }
  }
  Fr::zero()
}

///|
priv struct PoseidonParams {
  rc : Array[Fr]
  mds : Array[Array[Fr]]
}

///|
fn build_poseidon_params_t3() -> PoseidonParams {
  // field=1 (prime), sbox=0 (x^alpha), bits=254, t=3, rf=8, rp=57
  let lfsr = GrainLfsr::new(1, 0, 254, poseidon_t, poseidon_rf, poseidon_rp)
  let total_rc = poseidon_rounds * poseidon_t
  let rc : Array[Fr] = []
  for _i = 0; _i < total_rc; _i = _i + 1 {
    rc.push(lfsr.next_fr())
  }
  // Invertible 3x3 Cauchy MDS matrix: M[i][j] = 1 / (x_i + y_j) with x_i = i, y_j = t + j
  let mds : Array[Array[Fr]] = []
  for i = 0; i < poseidon_t; i = i + 1 {
    let row : Array[Fr] = []
    for j = 0; j < poseidon_t; j = j + 1 {
      let denom = Fr::from_u64((i + poseidon_t + j).to_uint64())
      row.push(denom.inv().unwrap())
    }
    mds.push(row)
  }
  { rc, mds, }
}

///|
let poseidon_t3_params : PoseidonParams = build_poseidon_params_t3()

///|
fn fr_sbox5(x : Fr) -> Fr {
  let x2 = x.square()
  let x4 = x2.square()
  x4.mul(x)
}

///|
/// Native BN254 Poseidon permutation (t = 3, R_F = 8, R_P = 57, S(x) = x^5).
pub fn poseidon_permute(state_in : Array[Fr]) -> Array[Fr] {
  let p = poseidon_t3_params
  let st : FixedArray[Fr] = FixedArray::make(poseidon_t, Fr::zero())
  for i = 0; i < poseidon_t && i < state_in.length(); i = i + 1 {
    st[i] = state_in[i]
  }
  let half_f = poseidon_rf / 2
  let mut rc_idx = 0
  for r = 0; r < poseidon_rounds; r = r + 1 {
    // 1. AddRoundConstants
    for i = 0; i < poseidon_t; i = i + 1 {
      st[i] = st[i].add(p.rc[rc_idx])
      rc_idx += 1
    }
    // 2. SubWords (x^5 on all elements in full rounds, element 0 in partial rounds)
    let is_full = r < half_f || r >= half_f + poseidon_rp
    if is_full {
      for i = 0; i < poseidon_t; i = i + 1 {
        st[i] = fr_sbox5(st[i])
      }
    } else {
      st[0] = fr_sbox5(st[0])
    }
    // 3. MixLayer (MDS matrix multiplication)
    let next : FixedArray[Fr] = FixedArray::make(poseidon_t, Fr::zero())
    for i = 0; i < poseidon_t; i = i + 1 {
      let mut acc = Fr::zero()
      for j = 0; j < poseidon_t; j = j + 1 {
        acc = acc.add(p.mds[i][j].mul(st[j]))
      }
      next[i] = acc
    }
    for i = 0; i < poseidon_t; i = i + 1 {
      st[i] = next[i]
    }
  }
  [st[0], st[1], st[2]]
}

///|
/// Standard 2-to-1 BN254 Poseidon hash: `Poseidon([0, a, b])[0]`.
pub fn poseidon2(a : Fr, b : Fr) -> Fr {
  poseidon_permute([Fr::zero(), a, b])[0]
}

///|
/// Sponge hash of arbitrary-length `Fr` inputs using BN254 Poseidon (t=3, rate=2, capacity=1).
pub fn poseidon_hash(inputs : Array[Fr]) -> Fr {
  let mut st = [
    Fr::from_u64(inputs.length().to_uint64()),
    Fr::zero(),
    Fr::zero(),
  ]
  let mut idx = 0
  while idx < inputs.length() {
    st[1] = st[1].add(inputs[idx])
    if idx + 1 < inputs.length() {
      st[2] = st[2].add(inputs[idx + 1])
    }
    st = poseidon_permute(st)
    idx += 2
  }
  if inputs.is_empty() {
    st = poseidon_permute(st)
  }
  st[0]
}

///|
/// R1CS Gadget: BN254 Poseidon 2-to-1 compression inside `CircuitBuilder`
/// (exact 3 constraints per S-box -> 243 constraints per hash: 8*3*3 + 57*3 = 243).
pub fn CircuitBuilder::poseidon2(
  self : CircuitBuilder,
  a : Wire,
  b : Wire,
  label : String,
) -> Wire {
  let p = poseidon_t3_params
  // Maintain each state lane as an exact linear combination of (Wire, Fr) to avoid
  // extra constraints for AddRoundConstants and MDS linear mixing!
  let mut st_lc : Array[Array[(Wire, Fr)]] = [
    [],
    [(a, Fr::one())],
    [(b, Fr::one())],
  ]
  let mut st_val : Array[Fr] = [Fr::zero(), self.val(a), self.val(b)]

  fn apply_sbox(
    lc : Array[(Wire, Fr)],
    v : Fr,
    slabel : String,
  ) -> (Array[(Wire, Fr)], Fr) {
    let v2 = v.square()
    let w2 = self.alloc_private("\{slabel}_2", v2)
    self.enforce(lc, lc, [(w2, Fr::one())], "\{slabel}_sq")
    let v4 = v2.square()
    let w4 = self.alloc_private("\{slabel}_4", v4)
    self.enforce(
      [(w2, Fr::one())],
      [(w2, Fr::one())],
      [(w4, Fr::one())],
      "\{slabel}_q4",
    )
    let v5 = v4.mul(v)
    let w5 = self.alloc_private("\{slabel}_5", v5)
    self.enforce([(w4, Fr::one())], lc, [(w5, Fr::one())], "\{slabel}_q5")
    ([(w5, Fr::one())], v5)
  }

  let half_f = poseidon_rf / 2
  let mut rc_idx = 0
  for r = 0; r < poseidon_rounds; r = r + 1 {
    // 1. AddRoundConstants (zero constraints: pure LC update)
    for i = 0; i < poseidon_t; i = i + 1 {
      let c = p.rc[rc_idx]
      rc_idx += 1
      let next_lc = st_lc[i].copy()
      next_lc.push((self.one(), c))
      st_lc[i] = next_lc
      st_val[i] = st_val[i].add(c)
    }
    // 2. SubWords (3 constraints per S-box)
    let is_full = r < half_f || r >= half_f + poseidon_rp
    if is_full {
      for i = 0; i < poseidon_t; i = i + 1 {
        let (nlc, nv) = apply_sbox(st_lc[i], st_val[i], "\{label}_r\{r}_\{i}")
        st_lc[i] = nlc
        st_val[i] = nv
      }
    } else {
      let (nlc, nv) = apply_sbox(st_lc[0], st_val[0], "\{label}_r\{r}_0")
      st_lc[0] = nlc
      st_val[0] = nv
    }
    // 3. MixLayer (zero constraints: linear combination of LCs, deduplicated by Wire.tag
    //    so partial rounds never experience exponential term blowup!)
    let next_lcs : Array[Array[(Wire, Fr)]] = []
    let next_vals : Array[Fr] = []
    for i = 0; i < poseidon_t; i = i + 1 {
      let merged : Map[Int32, Fr] = Map([])
      let mut acc = Fr::zero()
      for j = 0; j < poseidon_t; j = j + 1 {
        let mij = p.mds[i][j]
        acc = acc.add(mij.mul(st_val[j]))
        for term in st_lc[j] {
          let tag = term.0.tag
          let delta = term.1.mul(mij)
          let prev = merged.get(tag).unwrap_or(Fr::zero())
          merged[tag] = prev.add(delta)
        }
      }
      let combined : Array[(Wire, Fr)] = []
      for tag, coeff in merged {
        if !coeff.is_zero() {
          combined.push(({ tag, }, coeff))
        }
      }
      next_lcs.push(combined)
      next_vals.push(acc)
    }
    st_lc = next_lcs
    st_val = next_vals
  }
  let out = self.alloc_private("\{label}_out", st_val[0])
  self.enforce(
    st_lc[0],
    [(self.one(), Fr::one())],
    [(out, Fr::one())],
    "\{label}_out_eq",
  )
  out
}

///|
/// Build an arbitrary-depth BN254 Poseidon Merkle membership proof circuit:
/// Public input: `root`. Private inputs: `leaf`, `siblings[0..depth]`, `path_is_left[0..depth]`.
/// Depth 4 = ~985 constraints; Depth 8 = ~1,970 constraints.
pub fn circuit_merkle_poseidon(
  leaf : Fr,
  siblings : Array[Fr],
  path_is_left : Array[Bool],
) -> (R1cs, Array[Fr]) raise ZkError {
  let depth = siblings.length()
  if depth == 0 || depth != path_is_left.length() {
    raise ZkError::InvalidInput(
      "merkle_poseidon requires non-empty equal-length siblings and path_is_left",
    )
  }
  // Compute expected root natively first
  let mut expected = leaf
  for i = 0; i < depth; i = i + 1 {
    expected = if path_is_left[i] {
      poseidon2(expected, siblings[i])
    } else {
      poseidon2(siblings[i], expected)
    }
  }
  let cb = CircuitBuilder::new("merkle_poseidon_d\{depth}")
  let root_pub = cb.alloc_public("root", expected)
  let mut cur = cb.alloc_private("leaf", leaf)
  for i = 0; i < depth; i = i + 1 {
    let sib = cb.alloc_private("sib_\{i}", siblings[i])
    let bit = cb.alloc_private(
      "dir_\{i}",
      if path_is_left[i] {
        Fr::one()
      } else {
        Fr::zero()
      },
    )
    cb.assert_bool(bit, "dir_bool_\{i}")
    // When bit == 1 (leaf is left): left = cur, right = sib; else left = sib, right = cur
    let left = cb.mux(bit, sib, cur, "left_\{i}")
    let right = cb.mux(bit, cur, sib, "right_\{i}")
    cur = cb.poseidon2(left, right, "p_\{i}")
  }
  cb.assert_eq(cur, root_pub, "root_match")
  cb.finalize()
}

///|
/// Build a Semaphore/Zcash-style private Poseidon commitment + nullifier + range-checked amount circuit.
/// Public outputs: `commitment = Poseidon2(secret, amount)`, `nullifier_hash = Poseidon2(nullifier, secret)`.
/// Private inputs: `secret`, `nullifier`, `amount` (constrained to `0 <= amount < 2^max_bits`).
pub fn circuit_poseidon_commit(
  secret : Fr,
  nullifier : Fr,
  amount : Int32,
  max_bits~ : Int32 = 16,
) -> (R1cs, Array[Fr]) raise ZkError {
  if max_bits <= 0 || max_bits > 62 {
    raise ZkError::InvalidInput("max_bits must be in 1..62")
  }
  if amount < 0 {
    raise ZkError::InvalidInput("amount must be non-negative")
  }
  let amount_fr = Fr::from_u64(amount.to_int64().reinterpret_as_uint64())
  let expected_commit = poseidon2(secret, amount_fr)
  let expected_nullifier = poseidon2(nullifier, secret)

  let cb = CircuitBuilder::new("poseidon_commit_\{max_bits}b")
  let pub_commit = cb.alloc_public("commitment", expected_commit)
  let pub_nullifier = cb.alloc_public("nullifier_hash", expected_nullifier)
  let w_secret = cb.alloc_private("secret", secret)
  let w_nullifier = cb.alloc_private("nullifier", nullifier)
  let w_amount = cb.alloc_private("amount", amount_fr)

  cb.assert_range(w_amount, max_bits, "amount_range")
  let computed_commit = cb.poseidon2(w_secret, w_amount, "commit_hash")
  let computed_nullifier = cb.poseidon2(w_nullifier, w_secret, "nullifier_hash")
  cb.assert_eq(computed_commit, pub_commit, "commit_eq")
  cb.assert_eq(computed_nullifier, pub_nullifier, "nullifier_eq")
  cb.finalize()
}