///|
/// Linear combination of R1CS wires: sum_i coeff_i * wire[idx_i].
#derive(Debug, Eq)
pub struct LinearCombination {
  terms : Array[(Int32, Fr)]
}

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

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

///|
pub fn LinearCombination::zero() -> LinearCombination {
  { terms: [], }
}

///|
pub fn LinearCombination::from_wire(wire : Int32) -> LinearCombination {
  { terms: [(wire, Fr::one())], }
}

///|
pub fn LinearCombination::from_const(c : Fr) -> LinearCombination {
  if c.is_zero() {
    { terms: [], }
  } else {
    { terms: [(0, c)], }
  }
}

///|
pub fn LinearCombination::add_term(
  self : LinearCombination,
  wire : Int32,
  coeff : Fr,
) -> LinearCombination {
  if coeff.is_zero() {
    return self
  }
  let next = self.terms.copy()
  next.push((wire, coeff))
  { terms: next, }
}

///|
pub fn LinearCombination::add_lc(
  self : LinearCombination,
  other : LinearCombination,
) -> LinearCombination {
  let next = self.terms.copy()
  for t in other.terms {
    next.push(t)
  }
  { terms: next, }
}

///|
pub fn LinearCombination::sub_lc(
  self : LinearCombination,
  other : LinearCombination,
) -> LinearCombination {
  let next = self.terms.copy()
  for t in other.terms {
    next.push((t.0, t.1.neg()))
  }
  { terms: next, }
}

///|
pub fn LinearCombination::scale(
  self : LinearCombination,
  s : Fr,
) -> LinearCombination {
  if s.is_zero() {
    return LinearCombination::zero()
  }
  let next : Array[(Int32, Fr)] = []
  for t in self.terms {
    next.push((t.0, t.1.mul(s)))
  }
  { terms: next, }
}

///|
pub fn LinearCombination::eval(
  self : LinearCombination,
  witness : Array[Fr],
) -> Fr {
  let mut acc = Fr::zero()
  for t in self.terms {
    acc = acc.add(t.1.mul(witness[t.0]))
  }
  acc
}

///|
/// A single Rank-1 Constraint: A(w) * B(w) = C(w).
#derive(Debug, Eq)
pub struct Constraint {
  a : LinearCombination
  b : LinearCombination
  c : LinearCombination
  label : String
}

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

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

///|
/// Rank-1 Constraint System (R1CS) following Circom/snarkjs wire layout:
/// wire 0 = constant 1, wires 1..=num_public = public signals,
/// wires (num_public+1)..num_wires = private/intermediate signals.
#derive(Debug, Eq)
pub struct R1cs {
  name : String
  num_public : Int32
  num_wires : Int32
  wire_names : Array[String]
  constraints : Array[Constraint]
}

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

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

///|
/// Check whether a full witness vector satisfies every constraint in the R1CS.
pub fn R1cs::check_witness(
  self : R1cs,
  witness : Array[Fr],
) -> Unit raise ZkError {
  if witness.length() != self.num_wires {
    raise ZkError::InvalidR1cs(
      "witness length \{witness.length()} != num_wires \{self.num_wires}",
    )
  }
  if witness[0] != Fr::one() {
    raise ZkError::UnsatisfiedConstraint("wire 0 must equal 1")
  }
  for i = 0; i < self.constraints.length(); i = i + 1 {
    let con = self.constraints[i]
    let lhs = con.a.eval(witness).mul(con.b.eval(witness))
    let rhs = con.c.eval(witness)
    if lhs != rhs {
      raise ZkError::UnsatisfiedConstraint(
        "constraint #\{i} (\{con.label}) failed: \{lhs} != \{rhs}",
      )
    }
  }
}

///|
pub fn R1cs::is_satisfied(self : R1cs, witness : Array[Fr]) -> Bool {
  try {
    self.check_witness(witness)
    true
  } catch {
    _ => false
  }
}

///|
/// Extract public inputs (wires 1..=num_public) from a full witness.
pub fn R1cs::public_inputs(self : R1cs, witness : Array[Fr]) -> Array[Fr] {
  let out : Array[Fr] = []
  for i = 1; i <= self.num_public; i = i + 1 {
    out.push(witness[i])
  }
  out
}

///|
/// Stateful R1CS builder with witness assignment tracking.
pub struct R1csBuilder {
  name : String
  mut num_public : Int32
  mut has_private : Bool
  wire_names : Array[String]
  witness : Array[Fr]
  constraints : Array[Constraint]
}

///|
pub fn R1csBuilder::new(name : String) -> R1csBuilder {
  {
    name,
    num_public: 0,
    has_private: false,
    wire_names: ["one"],
    witness: [Fr::one()],
    constraints: [],
  }
}

///|
/// Allocate a public signal wire (must be called before any private/intermediate wire).
pub fn R1csBuilder::alloc_public(
  self : R1csBuilder,
  name : String,
  value : Fr,
) -> Int32 raise ZkError {
  if self.has_private {
    raise ZkError::InvalidR1cs(
      "cannot allocate public wire after private wires",
    )
  }
  let idx = self.wire_names.length()
  self.wire_names.push(name)
  self.witness.push(value)
  self.num_public = self.num_public + 1
  idx
}

///|
/// Allocate a private or intermediate witness wire.
pub fn R1csBuilder::alloc_private(
  self : R1csBuilder,
  name : String,
  value : Fr,
) -> Int32 {
  self.has_private = true
  let idx = self.wire_names.length()
  self.wire_names.push(name)
  self.witness.push(value)
  idx
}

///|
/// Enforce a Rank-1 Constraint A * B = C.
pub fn R1csBuilder::enforce(
  self : R1csBuilder,
  a : LinearCombination,
  b : LinearCombination,
  c : LinearCombination,
  label~ : String = "",
) -> Unit {
  let lbl = if label.length() == 0 {
    "c\{self.constraints.length()}"
  } else {
    label
  }
  self.constraints.push({ a, b, c, label: lbl, })
}

///|
/// Finalize the R1CS and witness pair.
pub fn R1csBuilder::build(self : R1csBuilder) -> (R1cs, Array[Fr]) {
  let r1cs : R1cs = {
    name: self.name,
    num_public: self.num_public,
    num_wires: self.wire_names.length(),
    wire_names: self.wire_names.copy(),
    constraints: self.constraints.copy(),
  }
  (r1cs, self.witness.copy())
}

///|
/// Deterministic MiMC-7 round constants over BN254 F_r (10 rounds).
let mimc7_round_constants : FixedArray[UInt64] = [
  0UL, 0x1a2b3c4d5e6f7081UL, 0x2b3c4d5e6f708192UL, 0x3c4d5e6f708192a3UL, 0x4d5e6f708192a3b4UL,
  0x5e6f708192a3b4c5UL, 0x6f708192a3b4c5d6UL, 0x708192a3b4c5d6e7UL, 0x8192a3b4c5d6e7f8UL,
  0x92a3b4c5d6e7f809UL,
]

///|
/// Native MiMC-7 permutation (10 rounds): x_{i+1} = (x_i + k + c_i)^7, output = x_10 + k.
pub fn mimc7_hash(x_in : Fr, key : Fr) -> Fr {
  let mut x = x_in
  for i = 0; i < mimc7_round_constants.length(); i = i + 1 {
    let t = x.add(key).add(Fr::from_u64(mimc7_round_constants[i]))
    let t2 = t.square()
    let t4 = t2.square()
    let t6 = t4.mul(t2)
    x = t6.mul(t)
  }
  x.add(key)
}

///|
/// Add MiMC-7 gadget constraints inside an R1csBuilder; returns the output wire index.
fn add_mimc7_gadget(
  b : R1csBuilder,
  x_wire : Int32,
  k_wire : Int32,
  prefix : String,
) -> Int32 {
  let mut cur_wire = x_wire
  let mut cur_val = b.witness[x_wire]
  let k_val = b.witness[k_wire]
  for i = 0; i < mimc7_round_constants.length(); i = i + 1 {
    let ci = Fr::from_u64(mimc7_round_constants[i])
    let t_val = cur_val.add(k_val).add(ci)
    let t2_val = t_val.square()
    let t4_val = t2_val.square()
    let t6_val = t4_val.mul(t2_val)
    let t7_val = t6_val.mul(t_val)

    let t_lc = LinearCombination::from_wire(cur_wire)
      .add_term(k_wire, Fr::one())
      .add_term(0, ci)
    let t2_w = b.alloc_private("\{prefix}_r\{i}_t2", t2_val)
    b.enforce(
      t_lc,
      t_lc,
      LinearCombination::from_wire(t2_w),
      label="\{prefix}_r\{i}_sq1",
    )

    let t4_w = b.alloc_private("\{prefix}_r\{i}_t4", t4_val)
    b.enforce(
      LinearCombination::from_wire(t2_w),
      LinearCombination::from_wire(t2_w),
      LinearCombination::from_wire(t4_w),
      label="\{prefix}_r\{i}_sq2",
    )

    let t6_w = b.alloc_private("\{prefix}_r\{i}_t6", t6_val)
    b.enforce(
      LinearCombination::from_wire(t4_w),
      LinearCombination::from_wire(t2_w),
      LinearCombination::from_wire(t6_w),
      label="\{prefix}_r\{i}_mul6",
    )

    let t7_w = b.alloc_private("\{prefix}_r\{i}_t7", t7_val)
    b.enforce(
      LinearCombination::from_wire(t6_w),
      t_lc,
      LinearCombination::from_wire(t7_w),
      label="\{prefix}_r\{i}_mul7",
    )

    cur_wire = t7_w
    cur_val = t7_val
  }
  let out_val = cur_val.add(k_val)
  let out_w = b.alloc_private("\{prefix}_out", out_val)
  b.enforce(
    LinearCombination::from_wire(cur_wire).add_term(k_wire, Fr::one()),
    LinearCombination::from_const(Fr::one()),
    LinearCombination::from_wire(out_w),
    label="\{prefix}_final",
  )
  out_w
}

///|
/// Built-in Circuit 1: Vitalik's classic cubic equation x^3 + x + 5 = y.
/// Public: [y]. Private: x.
pub fn circuit_cubic(x : Fr) -> (R1cs, Array[Fr]) raise ZkError {
  let x2 = x.square()
  let x3 = x2.mul(x)
  let y = x3.add(x).add(Fr::from_u64(5UL))

  let b = R1csBuilder::new("cubic")
  let y_w = b.alloc_public("y", y)
  let x_w = b.alloc_private("x", x)
  let x2_w = b.alloc_private("x2", x2)
  let x3_w = b.alloc_private("x3", x3)

  b.enforce(
    LinearCombination::from_wire(x_w),
    LinearCombination::from_wire(x_w),
    LinearCombination::from_wire(x2_w),
    label="x_sq",
  )
  b.enforce(
    LinearCombination::from_wire(x2_w),
    LinearCombination::from_wire(x_w),
    LinearCombination::from_wire(x3_w),
    label="x_cube",
  )
  b.enforce(
    LinearCombination::from_wire(x3_w)
    .add_term(x_w, Fr::one())
    .add_term(0, Fr::from_u64(5UL)),
    LinearCombination::from_const(Fr::one()),
    LinearCombination::from_wire(y_w),
    label="cubic_eq",
  )
  b.build()
}

///|
/// Built-in Circuit 2: Non-trivial integer factorization a * b = n with a != 1 and b != 1.
/// Public: [n]. Private: a, b.
pub fn circuit_factor(a : Fr, b_val : Fr) -> (R1cs, Array[Fr]) raise ZkError {
  let n = a.mul(b_val)
  let a_m1 = a.sub(Fr::one())
  let b_m1 = b_val.sub(Fr::one())
  let a_inv = match a_m1.inv() {
    None => raise ZkError::InvalidInput("factor a must not equal 1")
    Some(v) => v
  }
  let b_inv = match b_m1.inv() {
    None => raise ZkError::InvalidInput("factor b must not equal 1")
    Some(v) => v
  }

  let builder = R1csBuilder::new("factor")
  let n_w = builder.alloc_public("n", n)
  let a_w = builder.alloc_private("a", a)
  let b_w = builder.alloc_private("b", b_val)
  let a_inv_w = builder.alloc_private("a_m1_inv", a_inv)
  let b_inv_w = builder.alloc_private("b_m1_inv", b_inv)

  builder.enforce(
    LinearCombination::from_wire(a_w),
    LinearCombination::from_wire(b_w),
    LinearCombination::from_wire(n_w),
    label="a_mul_b",
  )
  builder.enforce(
    LinearCombination::from_wire(a_w).add_term(0, Fr::one().neg()),
    LinearCombination::from_wire(a_inv_w),
    LinearCombination::from_const(Fr::one()),
    label="a_neq_1",
  )
  builder.enforce(
    LinearCombination::from_wire(b_w).add_term(0, Fr::one().neg()),
    LinearCombination::from_wire(b_inv_w),
    LinearCombination::from_const(Fr::one()),
    label="b_neq_1",
  )
  builder.build()
}

///|
/// Built-in Circuit 3: MiMC-7 hash preimage proof H(preimage, key) = digest.
/// Public: [digest]. Private: preimage, key.
pub fn circuit_mimc7(
  preimage : Fr,
  key : Fr,
) -> (R1cs, Array[Fr]) raise ZkError {
  let digest = mimc7_hash(preimage, key)
  let b = R1csBuilder::new("mimc7")
  let d_w = b.alloc_public("digest", digest)
  let p_w = b.alloc_private("preimage", preimage)
  let k_w = b.alloc_private("key", key)
  let out_w = add_mimc7_gadget(b, p_w, k_w, "mimc")
  b.enforce(
    LinearCombination::from_wire(out_w),
    LinearCombination::from_const(Fr::one()),
    LinearCombination::from_wire(d_w),
    label="digest_eq",
  )
  b.build()
}

///|
/// Built-in Circuit 4: 2-level MiMC-7 Merkle tree membership proof.
/// Public: [root]. Private: leaf, sibling0, dir0 (0/1), sibling1, dir1 (0/1).
pub fn circuit_merkle_mimc(
  leaf : Fr,
  sibling0 : Fr,
  dir0 : Bool,
  sibling1 : Fr,
  dir1 : Bool,
) -> (R1cs, Array[Fr]) raise ZkError {
  let d0 = if dir0 { Fr::one() } else { Fr::zero() }
  let d1 = if dir1 { Fr::one() } else { Fr::zero() }
  let (l0, r0) = if dir0 { (sibling0, leaf) } else { (leaf, sibling0) }
  let mid = mimc7_hash(l0, r0)
  let (l1, r1) = if dir1 { (sibling1, mid) } else { (mid, sibling1) }
  let root = mimc7_hash(l1, r1)

  let b = R1csBuilder::new("merkle_mimc")
  let root_w = b.alloc_public("root", root)
  let leaf_w = b.alloc_private("leaf", leaf)
  let s0_w = b.alloc_private("sibling0", sibling0)
  let d0_w = b.alloc_private("dir0", d0)
  let s1_w = b.alloc_private("sibling1", sibling1)
  let d1_w = b.alloc_private("dir1", d1)

  // Boolean constraints on dir0, dir1
  b.enforce(
    LinearCombination::from_wire(d0_w),
    LinearCombination::from_const(Fr::one()).sub_lc(
      LinearCombination::from_wire(d0_w),
    ),
    LinearCombination::zero(),
    label="dir0_bool",
  )
  b.enforce(
    LinearCombination::from_wire(d1_w),
    LinearCombination::from_const(Fr::one()).sub_lc(
      LinearCombination::from_wire(d1_w),
    ),
    LinearCombination::zero(),
    label="dir1_bool",
  )

  // Level 0 conditional swap: left0 = leaf + d0 * (s0 - leaf), right0 = leaf + s0 - left0
  let l0_w = b.alloc_private("left0", l0)
  let r0_w = b.alloc_private("right0", r0)
  b.enforce(
    LinearCombination::from_wire(d0_w),
    LinearCombination::from_wire(s0_w).sub_lc(
      LinearCombination::from_wire(leaf_w),
    ),
    LinearCombination::from_wire(l0_w).sub_lc(
      LinearCombination::from_wire(leaf_w),
    ),
    label="swap0_left",
  )
  b.enforce(
    LinearCombination::from_wire(leaf_w)
    .add_term(s0_w, Fr::one())
    .sub_lc(LinearCombination::from_wire(l0_w)),
    LinearCombination::from_const(Fr::one()),
    LinearCombination::from_wire(r0_w),
    label="swap0_right",
  )
  let mid_w = add_mimc7_gadget(b, l0_w, r0_w, "lvl0")

  // Level 1 conditional swap
  let l1_w = b.alloc_private("left1", l1)
  let r1_w = b.alloc_private("right1", r1)
  b.enforce(
    LinearCombination::from_wire(d1_w),
    LinearCombination::from_wire(s1_w).sub_lc(
      LinearCombination::from_wire(mid_w),
    ),
    LinearCombination::from_wire(l1_w).sub_lc(
      LinearCombination::from_wire(mid_w),
    ),
    label="swap1_left",
  )
  b.enforce(
    LinearCombination::from_wire(mid_w)
    .add_term(s1_w, Fr::one())
    .sub_lc(LinearCombination::from_wire(l1_w)),
    LinearCombination::from_const(Fr::one()),
    LinearCombination::from_wire(r1_w),
    label="swap1_right",
  )
  let calc_root_w = add_mimc7_gadget(b, l1_w, r1_w, "lvl1")
  b.enforce(
    LinearCombination::from_wire(calc_root_w),
    LinearCombination::from_const(Fr::one()),
    LinearCombination::from_wire(root_w),
    label="root_eq",
  )
  b.build()
}

///|
/// Built-in Circuit 5: 8-bit binary decomposition range proof (0 <= value < 256)
/// with MiMC-7 commitment commit = H(value, salt).
/// Public: [commit]. Private: value, salt, bits b0..b7.
pub fn circuit_range8(
  value : Int32,
  salt : Fr,
) -> (R1cs, Array[Fr]) raise ZkError {
  if value < 0 || value > 255 {
    raise ZkError::InvalidInput("range8 value must be in 0..255, got \{value}")
  }
  let v_fr = Fr::from_u64(value.to_uint64())
  let commit = mimc7_hash(v_fr, salt)

  let b = R1csBuilder::new("range8")
  let c_w = b.alloc_public("commit", commit)
  let v_w = b.alloc_private("value", v_fr)
  let s_w = b.alloc_private("salt", salt)

  let mut sum_lc = LinearCombination::zero()
  let mut pow2 = Fr::one()
  for i = 0; i < 8; i = i + 1 {
    let bit_val = if ((value >> i) & 1) == 1 { Fr::one() } else { Fr::zero() }
    let bw = b.alloc_private("bit_\{i}", bit_val)
    b.enforce(
      LinearCombination::from_wire(bw),
      LinearCombination::from_const(Fr::one()).sub_lc(
        LinearCombination::from_wire(bw),
      ),
      LinearCombination::zero(),
      label="bit_\{i}_bool",
    )
    sum_lc = sum_lc.add_term(bw, pow2)
    pow2 = pow2.double()
  }
  b.enforce(
    sum_lc,
    LinearCombination::from_const(Fr::one()),
    LinearCombination::from_wire(v_w),
    label="bit_decomp",
  )
  let out_w = add_mimc7_gadget(b, v_w, s_w, "commit")
  b.enforce(
    LinearCombination::from_wire(out_w),
    LinearCombination::from_const(Fr::one()),
    LinearCombination::from_wire(c_w),
    label="commit_eq",
  )
  b.build()
}