///|
/// Standard `iden3` binary `.r1cs` (v1) and `.wtns` (v2) encoder & decoder
/// compatible with Circom and snarkjs BN254 scalar field F_r.
fn write_u32_le(buf : Buffer, v : UInt32) -> Unit {
  buf.write_byte((v & 0xffU).to_byte())
  buf.write_byte(((v >> 8) & 0xffU).to_byte())
  buf.write_byte(((v >> 16) & 0xffU).to_byte())
  buf.write_byte(((v >> 24) & 0xffU).to_byte())
}

///|
fn write_u64_le(buf : Buffer, v : UInt64) -> Unit {
  for i = 0; i < 8; i = i + 1 {
    buf.write_byte(((v >> (i * 8)) & 0xffUL).to_byte())
  }
}

///|
fn write_u256_le(buf : Buffer, u : U256) -> Unit {
  write_u64_le(buf, u.l0)
  write_u64_le(buf, u.l1)
  write_u64_le(buf, u.l2)
  write_u64_le(buf, u.l3)
}

///|
fn read_u32_le(data : BytesView, off : Int32) -> UInt32 raise ZkError {
  if off < 0 || off + 4 > data.length() {
    raise ZkError::InvalidInput("unexpected EOF reading u32 at offset \{off}")
  }
  data[off].to_uint() |
  (data[off + 1].to_uint() << 8) |
  (data[off + 2].to_uint() << 16) |
  (data[off + 3].to_uint() << 24)
}

///|
fn read_u64_le(data : BytesView, off : Int32) -> UInt64 raise ZkError {
  if off < 0 || off + 8 > data.length() {
    raise ZkError::InvalidInput("unexpected EOF reading u64 at offset \{off}")
  }
  let mut acc = 0UL
  for i = 0; i < 8; i = i + 1 {
    acc = acc | (data[off + i].to_uint64() << (i * 8))
  }
  acc
}

///|
fn read_u256_le(data : BytesView, off : Int32) -> U256 raise ZkError {
  if off < 0 || off + 32 > data.length() {
    raise ZkError::InvalidInput("unexpected EOF reading u256 at offset \{off}")
  }
  U256::new(
    read_u64_le(data, off),
    read_u64_le(data, off + 8),
    read_u64_le(data, off + 16),
    read_u64_le(data, off + 24),
  )
}

///|
/// Encode an `R1cs` into the official `iden3/r1csfile` v1 binary format (`.r1cs`).
pub fn encode_iden3_r1cs(r1cs : R1cs) -> Bytes {
  // Build Section 1 (Header): 4 + 32 + 4*6 = 60 bytes
  let sec1 = Buffer()
  write_u32_le(sec1, 32U) // field_size = 32 bytes (BN254 Fr)
  write_u256_le(sec1, fr_modulus)
  write_u32_le(sec1, r1cs.num_wires.reinterpret_as_uint())
  write_u32_le(sec1, r1cs.num_public.reinterpret_as_uint()) // nPubOut
  write_u32_le(sec1, 0U) // nPubIn (public signals total = nPubOut + nPubIn)
  let n_prv = if r1cs.num_wires > 1 + r1cs.num_public {
    r1cs.num_wires - 1 - r1cs.num_public
  } else {
    0
  }
  write_u32_le(sec1, n_prv.reinterpret_as_uint())
  write_u64_le(sec1, r1cs.num_wires.to_uint64()) // nLabels
  write_u32_le(sec1, r1cs.constraints.length().reinterpret_as_uint())
  let sec1_bytes = sec1.to_bytes()

  // Build Section 2 (Constraints)
  let sec2 = Buffer()
  fn write_lc(lc : LinearCombination) -> Unit {
    write_u32_le(sec2, lc.terms.length().reinterpret_as_uint())
    for term in lc.terms {
      write_u32_le(sec2, term.0.reinterpret_as_uint())
      write_u256_le(sec2, term.1.to_u256())
    }
  }
  for con in r1cs.constraints {
    write_lc(con.a)
    write_lc(con.b)
    write_lc(con.c)
  }
  let sec2_bytes = sec2.to_bytes()

  // Build Section 3 (Wire2Label identity map)
  let sec3 = Buffer()
  for i = 0; i < r1cs.num_wires; i = i + 1 {
    write_u64_le(sec3, i.to_uint64())
  }
  let sec3_bytes = sec3.to_bytes()

  // Assemble file
  let out = Buffer()
  out.write_bytesview(b"r1cs"[:])
  write_u32_le(out, 1U) // version = 1
  write_u32_le(out, 3U) // 3 sections
  write_u32_le(out, 1U)
  write_u64_le(out, sec1_bytes.length().to_uint64())
  out.write_bytesview(sec1_bytes[:])
  write_u32_le(out, 2U)
  write_u64_le(out, sec2_bytes.length().to_uint64())
  out.write_bytesview(sec2_bytes[:])
  write_u32_le(out, 3U)
  write_u64_le(out, sec3_bytes.length().to_uint64())
  out.write_bytesview(sec3_bytes[:])
  out.to_bytes()
}

///|
/// Decode an official `iden3/r1csfile` v1 binary (`.r1cs`) into a `moon-zk` `R1cs`.
pub fn decode_iden3_r1cs(
  data : BytesView,
  name~ : String = "iden3_r1cs",
) -> R1cs raise ZkError {
  if data.length() < 12 ||
    data[0] != b'r' ||
    data[1] != b'1' ||
    data[2] != b'c' ||
    data[3] != b's' {
    raise ZkError::InvalidR1cs("invalid .r1cs magic header (expected 'r1cs')")
  }
  let version = read_u32_le(data, 4)
  if version != 1U {
    raise ZkError::InvalidR1cs(
      "unsupported .r1cs version \{version} (expected 1)",
    )
  }
  let n_sections = read_u32_le(data, 8).reinterpret_as_int()
  let mut off = 12
  let mut sec1_off = -1
  let mut sec1_len = 0
  let mut sec2_off = -1
  let mut sec2_len = 0
  for _s = 0; _s < n_sections; _s = _s + 1 {
    let stype = read_u32_le(data, off)
    let slen = read_u64_le(data, off + 4).to_int()
    off += 12
    if off + slen > data.length() {
      raise ZkError::InvalidR1cs("section \{stype} exceeds file length")
    }
    if stype == 1U {
      sec1_off = off
      sec1_len = slen
    } else if stype == 2U {
      sec2_off = off
      sec2_len = slen
    }
    off += slen
  }
  if sec1_off < 0 || sec2_off < 0 {
    raise ZkError::InvalidR1cs(
      "missing required section 1 (header) or 2 (constraints)",
    )
  }
  if sec1_len < 60 {
    raise ZkError::InvalidR1cs("section 1 header too short")
  }
  let field_sz = read_u32_le(data, sec1_off)
  if field_sz != 32U {
    raise ZkError::InvalidR1cs(
      "unsupported field size \{field_sz} (expected 32 for BN254)",
    )
  }
  let prime = read_u256_le(data, sec1_off + 4)
  if prime != fr_modulus {
    raise ZkError::InvalidR1cs("prime modulus does not match BN254 Fr")
  }
  let num_wires = read_u32_le(data, sec1_off + 36).reinterpret_as_int()
  let n_pub_out = read_u32_le(data, sec1_off + 40).reinterpret_as_int()
  let n_pub_in = read_u32_le(data, sec1_off + 44).reinterpret_as_int()
  let num_public = n_pub_out + n_pub_in
  let m_constraints = read_u32_le(data, sec1_off + 60).reinterpret_as_int()

  let mut cur = sec2_off
  let sec2_end = sec2_off + sec2_len
  fn read_lc() -> LinearCombination raise ZkError {
    let n_terms = read_u32_le(data, cur).reinterpret_as_int()
    cur += 4
    let terms : Array[(Int32, Fr)] = []
    for _t = 0; _t < n_terms; _t = _t + 1 {
      let wid = read_u32_le(data, cur).reinterpret_as_int()
      let coeff = Fr::from_u256(read_u256_le(data, cur + 4))
      cur += 36
      if wid < 0 || wid >= num_wires {
        raise ZkError::InvalidR1cs(
          "wire id \{wid} out of range 0..\{num_wires}",
        )
      }
      terms.push((wid, coeff))
    }
    { terms, }
  }
  let constraints : Array[Constraint] = []
  for i = 0; i < m_constraints; i = i + 1 {
    if cur > sec2_end {
      raise ZkError::InvalidR1cs(
        "constraints section truncated at constraint \{i}",
      )
    }
    let a = read_lc()
    let b = read_lc()
    let c = read_lc()
    constraints.push({ a, b, c, label: "c\{i}", })
  }
  let wire_names : Array[String] = []
  for i = 0; i < num_wires; i = i + 1 {
    wire_names.push(if i == 0 { "1" } else { "w\{i}" })
  }
  { name, num_public, num_wires, wire_names, constraints, }
}

///|
/// Encode a witness array into the official `iden3/wtns` v2 binary format (`.wtns`).
pub fn encode_iden3_wtns(witness : Array[Fr]) -> Bytes {
  let sec1 = Buffer()
  write_u32_le(sec1, 32U)
  write_u256_le(sec1, fr_modulus)
  write_u32_le(sec1, witness.length().reinterpret_as_uint())
  let sec1_bytes = sec1.to_bytes()

  let sec2 = Buffer()
  for w in witness {
    write_u256_le(sec2, w.to_u256())
  }
  let sec2_bytes = sec2.to_bytes()

  let out = Buffer()
  out.write_bytesview(b"wtns"[:])
  write_u32_le(out, 2U)
  write_u32_le(out, 2U)
  write_u32_le(out, 1U)
  write_u64_le(out, sec1_bytes.length().to_uint64())
  out.write_bytesview(sec1_bytes[:])
  write_u32_le(out, 2U)
  write_u64_le(out, sec2_bytes.length().to_uint64())
  out.write_bytesview(sec2_bytes[:])
  out.to_bytes()
}

///|
/// Decode an official `iden3/wtns` v2 binary file (`.wtns`) into a `Fr` witness vector.
pub fn decode_iden3_wtns(data : BytesView) -> Array[Fr] raise ZkError {
  if data.length() < 12 ||
    data[0] != b'w' ||
    data[1] != b't' ||
    data[2] != b'n' ||
    data[3] != b's' {
    raise ZkError::InvalidInput("invalid .wtns magic header (expected 'wtns')")
  }
  let version = read_u32_le(data, 4)
  if version != 2U {
    raise ZkError::InvalidInput(
      "unsupported .wtns version \{version} (expected 2)",
    )
  }
  let n_sections = read_u32_le(data, 8).reinterpret_as_int()
  let mut off = 12
  let mut sec1_off = -1
  let mut sec2_off = -1
  let mut sec2_len = 0
  for _s = 0; _s < n_sections; _s = _s + 1 {
    let stype = read_u32_le(data, off)
    let slen = read_u64_le(data, off + 4).to_int()
    off += 12
    if off + slen > data.length() {
      raise ZkError::InvalidInput("wtns section \{stype} exceeds file length")
    }
    if stype == 1U {
      sec1_off = off
    } else if stype == 2U {
      sec2_off = off
      sec2_len = slen
    }
    off += slen
  }
  if sec1_off < 0 || sec2_off < 0 {
    raise ZkError::InvalidInput("missing required wtns section 1 or 2")
  }
  let field_sz = read_u32_le(data, sec1_off)
  if field_sz != 32U {
    raise ZkError::InvalidInput("unsupported wtns field size \{field_sz}")
  }
  let prime = read_u256_le(data, sec1_off + 4)
  if prime != fr_modulus {
    raise ZkError::InvalidInput("wtns prime does not match BN254 Fr")
  }
  let n_witness = read_u32_le(data, sec1_off + 36).reinterpret_as_int()
  if sec2_len < n_witness * 32 {
    raise ZkError::InvalidInput(
      "wtns section 2 too short for \{n_witness} field elements",
    )
  }
  let out : Array[Fr] = []
  for i = 0; i < n_witness; i = i + 1 {
    out.push(Fr::from_u256(read_u256_le(data, sec2_off + i * 32)))
  }
  out
}