///|
/// Ergonomic composable R1CS CircuitBuilder DSL and standard ZK gadget library.
/// Maintains Circom/snarkjs wire layout: wire 0 = 1, public wires allocated first,
/// followed by private & intermediate wires.
pub struct CircuitBuilder {
  name : String
  pub_wires : Array[(String, Fr)]
  priv_wires : Array[(String, Fr)]
  // Raw constraints stored with tagged wire IDs:
  //   0 = constant 1
  //   > 0 = public wire index (1-based into pub_wires)
  //   < 0 = private wire index (-1 - idx into priv_wires)
  raw_constraints : Array[
    (Array[(Int32, Fr)], Array[(Int32, Fr)], Array[(Int32, Fr)], String),
  ]
}

///|
/// Handle to a wire inside a `CircuitBuilder`.
#derive(Debug, Eq)
pub struct Wire {
  tag : Int32
}

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

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

///|
pub fn CircuitBuilder::new(name : String) -> CircuitBuilder {
  { name, pub_wires: [], priv_wires: [], raw_constraints: [], }
}

///|
pub fn CircuitBuilder::one(_self : CircuitBuilder) -> Wire {
  { tag: 0, }
}

///|
pub fn CircuitBuilder::alloc_public(
  self : CircuitBuilder,
  label : String,
  value : Fr,
) -> Wire {
  self.pub_wires.push((label, value))
  { tag: self.pub_wires.length(), }
}

///|
pub fn CircuitBuilder::alloc_private(
  self : CircuitBuilder,
  label : String,
  value : Fr,
) -> Wire {
  let idx = self.priv_wires.length()
  self.priv_wires.push((label, value))
  { tag: -1 - idx, }
}

///|
pub fn CircuitBuilder::val(self : CircuitBuilder, w : Wire) -> Fr {
  if w.tag == 0 {
    Fr::one()
  } else if w.tag > 0 {
    self.pub_wires[w.tag - 1].1
  } else {
    self.priv_wires[-1 - w.tag].1
  }
}

///|
pub fn CircuitBuilder::enforce(
  self : CircuitBuilder,
  a : Array[(Wire, Fr)],
  b : Array[(Wire, Fr)],
  c : Array[(Wire, Fr)],
  label : String,
) -> Unit {
  let ra : Array[(Int32, Fr)] = []
  for p in a {
    if !p.1.is_zero() {
      ra.push((p.0.tag, p.1))
    }
  }
  let rb : Array[(Int32, Fr)] = []
  for p in b {
    if !p.1.is_zero() {
      rb.push((p.0.tag, p.1))
    }
  }
  let rc : Array[(Int32, Fr)] = []
  for p in c {
    if !p.1.is_zero() {
      rc.push((p.0.tag, p.1))
    }
  }
  self.raw_constraints.push((ra, rb, rc, label))
}

///|
pub fn CircuitBuilder::assert_eq(
  self : CircuitBuilder,
  a : Wire,
  b : Wire,
  label : String,
) -> Unit {
  self.enforce(
    [(a, Fr::one())],
    [(self.one(), Fr::one())],
    [(b, Fr::one())],
    label,
  )
}

///|
pub fn CircuitBuilder::assert_const(
  self : CircuitBuilder,
  a : Wire,
  c : Fr,
  label : String,
) -> Unit {
  self.enforce(
    [(a, Fr::one())],
    [(self.one(), Fr::one())],
    [(self.one(), c)],
    label,
  )
}

///|
pub fn CircuitBuilder::assert_bool(
  self : CircuitBuilder,
  b : Wire,
  label : String,
) -> Unit {
  // b * (1 - b) = 0
  self.enforce(
    [(b, Fr::one())],
    [(self.one(), Fr::one()), (b, Fr::one().neg())],
    [],
    label,
  )
}

///|
pub fn CircuitBuilder::mul(
  self : CircuitBuilder,
  a : Wire,
  b : Wire,
  label : String,
) -> Wire {
  let out = self.alloc_private(label, self.val(a).mul(self.val(b)))
  self.enforce([(a, Fr::one())], [(b, Fr::one())], [(out, Fr::one())], label)
  out
}

///|
pub fn CircuitBuilder::add(
  self : CircuitBuilder,
  a : Wire,
  b : Wire,
  label : String,
) -> Wire {
  let out = self.alloc_private(label, self.val(a).add(self.val(b)))
  self.enforce(
    [(a, Fr::one()), (b, Fr::one())],
    [(self.one(), Fr::one())],
    [(out, Fr::one())],
    label,
  )
  out
}

///|
pub fn CircuitBuilder::sub(
  self : CircuitBuilder,
  a : Wire,
  b : Wire,
  label : String,
) -> Wire {
  let out = self.alloc_private(label, self.val(a).sub(self.val(b)))
  self.enforce(
    [(a, Fr::one()), (b, Fr::one().neg())],
    [(self.one(), Fr::one())],
    [(out, Fr::one())],
    label,
  )
  out
}

///|
/// Standard Circom `IsZero` gadget: returns 1 if `x == 0`, else 0 (2 constraints).
pub fn CircuitBuilder::is_zero(
  self : CircuitBuilder,
  x : Wire,
  label : String,
) -> Wire {
  let xv = self.val(x)
  let (inv_v, out_v) = if xv.is_zero() {
    (Fr::zero(), Fr::one())
  } else {
    (xv.inv().unwrap(), Fr::zero())
  }
  let inv = self.alloc_private("\{label}_inv", inv_v)
  let out = self.alloc_private(label, out_v)
  // x * inv = 1 - out
  self.enforce(
    [(x, Fr::one())],
    [(inv, Fr::one())],
    [(self.one(), Fr::one()), (out, Fr::one().neg())],
    "\{label}_inv_check",
  )
  // x * out = 0
  self.enforce([(x, Fr::one())], [(out, Fr::one())], [], "\{label}_zero_check")
  out
}

///|
/// Standard `IsEqual(a, b)` gadget: returns 1 if `a == b`, else 0.
pub fn CircuitBuilder::is_equal(
  self : CircuitBuilder,
  a : Wire,
  b : Wire,
  label : String,
) -> Wire {
  let diff = self.sub(a, b, "\{label}_diff")
  self.is_zero(diff, label)
}

///|
/// Standard `Mux(sel, if_zero, if_one)` gadget (1 constraint, assumes `sel` is boolean):
/// out = if_zero + sel * (if_one - if_zero).
pub fn CircuitBuilder::mux(
  self : CircuitBuilder,
  sel : Wire,
  if_zero : Wire,
  if_one : Wire,
  label : String,
) -> Wire {
  let sv = self.val(sel)
  let z0 = self.val(if_zero)
  let z1 = self.val(if_one)
  let out = self.alloc_private(label, z0.add(sv.mul(z1.sub(z0))))
  // sel * (if_one - if_zero) = out - if_zero
  self.enforce(
    [(sel, Fr::one())],
    [(if_one, Fr::one()), (if_zero, Fr::one().neg())],
    [(out, Fr::one()), (if_zero, Fr::one().neg())],
    label,
  )
  out
}

///|
/// Standard `Num2Bits(n)` gadget: decomposes `x` into `n` little-endian boolean wires.
pub fn CircuitBuilder::num2bits(
  self : CircuitBuilder,
  x : Wire,
  num_bits : Int32,
  label : String,
) -> Array[Wire] {
  let u = self.val(x).to_u256()
  let bits : Array[Wire] = []
  let sum_terms : Array[(Wire, Fr)] = []
  let mut pow2 = Fr::one()
  let two = Fr::from_u64(2UL)
  for i = 0; i < num_bits; i = i + 1 {
    let limb = i / 64
    let sh = i % 64
    let word = match limb {
      0 => u.l0
      1 => u.l1
      2 => u.l2
      _ => u.l3
    }
    let bit_set = ((word >> sh) & 1UL) != 0UL
    let bw = self.alloc_private(
      "\{label}_b\{i}",
      if bit_set {
        Fr::one()
      } else {
        Fr::zero()
      },
    )
    self.assert_bool(bw, "\{label}_bool_\{i}")
    bits.push(bw)
    sum_terms.push((bw, pow2))
    pow2 = pow2.mul(two)
  }
  self.enforce(
    sum_terms,
    [(self.one(), Fr::one())],
    [(x, Fr::one())],
    "\{label}_sum",
  )
  bits
}

///|
/// Standard `LessThan(n)` gadget: returns 1 iff `a < b` for n-bit unsigned integers (`n <= 62`).
pub fn CircuitBuilder::less_than(
  self : CircuitBuilder,
  a : Wire,
  b : Wire,
  num_bits : Int32,
  label : String,
) -> Wire {
  // diff = a + 2^n - b; bit n of diff is 0 iff a < b, so out = 1 - bit[n]
  let pow2n = Fr::from_u64(1UL << num_bits)
  let diff_val = self.val(a).add(pow2n).sub(self.val(b))
  let diff = self.alloc_private("\{label}_diff", diff_val)
  self.enforce(
    [(a, Fr::one()), (self.one(), pow2n), (b, Fr::one().neg())],
    [(self.one(), Fr::one())],
    [(diff, Fr::one())],
    "\{label}_diff_eq",
  )
  let bits = self.num2bits(diff, num_bits + 1, "\{label}_bits")
  let msb = bits[num_bits]
  let out = self.alloc_private(label, Fr::one().sub(self.val(msb)))
  self.enforce(
    [(self.one(), Fr::one()), (msb, Fr::one().neg())],
    [(self.one(), Fr::one())],
    [(out, Fr::one())],
    "\{label}_out",
  )
  out
}

///|
/// Enforce `0 <= x < 2^num_bits` by decomposing `x` into `num_bits` boolean wires.
pub fn CircuitBuilder::assert_range(
  self : CircuitBuilder,
  x : Wire,
  num_bits : Int32,
  label : String,
) -> Unit {
  ignore(self.num2bits(x, num_bits, label))
}

///|
/// Enforce `a < b` for `num_bits`-bit unsigned integers (`num_bits <= 62`).
pub fn CircuitBuilder::assert_less_than(
  self : CircuitBuilder,
  a : Wire,
  b : Wire,
  num_bits : Int32,
  label : String,
) -> Unit {
  let lt = self.less_than(a, b, num_bits, label)
  self.assert_const(lt, Fr::one(), "\{label}_must_be_true")
}

///|
/// Finalize the builder into a verified Circom-layout `(R1cs, Array[Fr])`.
pub fn CircuitBuilder::finalize(
  self : CircuitBuilder,
) -> (R1cs, Array[Fr]) raise ZkError {
  let num_public = self.pub_wires.length()
  let num_wires = 1 + num_public + self.priv_wires.length()
  let wire_names : Array[String] = ["1"]
  let witness : Array[Fr] = [Fr::one()]
  for p in self.pub_wires {
    wire_names.push(p.0)
    witness.push(p.1)
  }
  for p in self.priv_wires {
    wire_names.push(p.0)
    witness.push(p.1)
  }
  fn resolve(tag : Int32) -> Int32 {
    if tag >= 0 {
      tag
    } else {
      1 + num_public + (-1 - tag)
    }
  }
  fn to_lc(raw : Array[(Int32, Fr)]) -> LinearCombination {
    let terms : Array[(Int32, Fr)] = []
    for t in raw {
      terms.push((resolve(t.0), t.1))
    }
    { terms, }
  }
  let constraints : Array[Constraint] = []
  for rc in self.raw_constraints {
    constraints.push({
      a: to_lc(rc.0),
      b: to_lc(rc.1),
      c: to_lc(rc.2),
      label: rc.3,
    })
  }
  let r1cs : R1cs = {
    name: self.name,
    num_public,
    num_wires,
    wire_names,
    constraints,
  }
  r1cs.check_witness(witness)
  (r1cs, witness)
}