///|
fn svg_escape(s : String) -> String {
  let buf = StringBuilder()
  for i = 0; i < s.length(); i = i + 1 {
    let ch = s[i].to_int().unsafe_to_char()
    match ch {
      '&' => buf.write_string("&")
      '<' => buf.write_string("<")
      '>' => buf.write_string(">")
      '"' => buf.write_string(""")
      _ => buf.write_char(ch)
    }
  }
  buf.to_string()
}

///|
fn short_dec(s : String, max_len : Int32) -> String {
  if s.length() <= max_len {
    s
  } else {
    let head = s[0:max_len - 6].to_owned()
    let tail = s[s.length() - 4:].to_owned()
    "\{head}..\{tail}"
  }
}

///|
/// Render a native SVG diagram of the R1CS constraint network (wires and multiplication gates).
pub fn render_r1cs_svg(r1cs : R1cs, witness~ : Array[Fr]? = None) -> String {
  let max_gates = if r1cs.constraints.length() > 14 {
    14
  } else {
    r1cs.constraints.length()
  }
  let width = 820
  let header_h = 72
  let row_h = 34
  let height = header_h + max_gates * row_h + 64
  let buf = StringBuilder()

  buf.write_string(
    "",
  )
  buf.write_string(
    "",
  )
  buf.write_string(
    "",
  )

  // Title and metadata badges
  buf.write_string(
    "R1CS Circuit: \{svg_escape(r1cs.name)}",
  )
  buf.write_string(
    "wires=\{r1cs.num_wires} (public=\{r1cs.num_public}, private=\{r1cs.num_wires - r1cs.num_public - 1}) | constraints=\{r1cs.constraints.length()}",
  )

  // Column headers
  let col_y = header_h + 4
  buf.write_string(
    "GATE",
  )
  buf.write_string(
    "A(w)",
  )
  buf.write_string(
    "B(w)",
  )
  buf.write_string(
    "C(w)",
  )
  buf.write_string(
    "CHECK",
  )

  // Track unique referenced wires using Map[Int, Bool] (v1.0.0-rc1 clean)
  let seen_wires : Map[Int32, Bool] = Map([])
  for i = 0; i < max_gates; i = i + 1 {
    let con = r1cs.constraints[i]
    for t in con.a.terms {
      seen_wires.set(t.0, true)
    }
    for t in con.b.terms {
      seen_wires.set(t.0, true)
    }
    for t in con.c.terms {
      seen_wires.set(t.0, true)
    }
    let y = header_h + 18 + i * row_h
    buf.write_string(
      "",
    )
    buf.write_string(
      "#\{i} \{svg_escape(short_dec(con.label, 14))}",
    )

    let (a_txt, b_txt, c_txt, ok_txt, ok_col) = match witness {
      Some(w) => {
        let av = con.a.eval(w)
        let bv = con.b.eval(w)
        let cv = con.c.eval(w)
        let ok = av.mul(bv) == cv
        (
          short_dec(av.to_decimal(), 18),
          short_dec(bv.to_decimal(), 18),
          short_dec(cv.to_decimal(), 18),
          if ok {
            "PASS"
          } else {
            "FAIL"
          },
          if ok {
            "#22c55e"
          } else {
            "#ef4444"
          },
        )
      }
      None =>
        (
          "\{con.a.terms.length()} terms",
          "\{con.b.terms.length()} terms",
          "\{con.c.terms.length()} terms",
          "R1CS",
          "#64748b",
        )
    }
    buf.write_string(
      "\{svg_escape(a_txt)}",
    )
    buf.write_string(
      "*",
    )
    buf.write_string(
      "\{svg_escape(b_txt)}",
    )
    buf.write_string(
      "=",
    )
    buf.write_string(
      "\{svg_escape(c_txt)}",
    )
    buf.write_string(
      "",
    )
    buf.write_string(
      "\{ok_txt}",
    )
  }

  let foot_y = header_h + 26 + max_gates * row_h
  let extra = if r1cs.constraints.length() > max_gates {
    " (+ \{r1cs.constraints.length() - max_gates} more gates)"
  } else {
    ""
  }
  buf.write_string(
    "active wires shown=\{seen_wires.length()}\{extra} | BN254 F_r",
  )
  buf.write_string("")
  buf.to_string()
}

///|
/// Render a native SVG summary of the 4-term Groth16 Optimal Ate Pairing check.
pub fn render_pairing_svg(
  circuit_name : String,
  num_constraints : Int32,
  num_wires : Int32,
  num_public : Int32,
  verified : Bool,
  proof : Proof,
) -> String {
  let status_text = if verified { "VERIFIED (PASS)" } else { "REJECTED (FAIL)" }
  let status_bg = if verified { "#14532d" } else { "#7f1d1d" }
  let status_fg = if verified { "#4ade80" } else { "#f87171" }
  let eq_sym = if verified { "= 1_GT" } else { "!= 1_GT" }
  let pa_short = short_dec(proof.a.x.to_decimal(), 20)
  let pb_short = short_dec(proof.b.x.c0.to_decimal(), 20)
  let pc_short = short_dec(proof.c.x.to_decimal(), 20)

  let buf = StringBuilder()
  buf.write_string(
    "",
  )
  buf.write_string(
    "",
  )
  buf.write_string(
    "Groth16 BN254 Pairing Verification: \{svg_escape(circuit_name)}",
  )
  buf.write_string(
    "",
  )
  buf.write_string(
    "\{status_text}",
  )

  // 4 pairing term boxes
  let terms : Array[(String, String, String)] = [
    ("e(-pi_a, pi_b)", "A.x=\{pa_short}", "#38bdf8"),
    ("e(alpha_1, beta_2)", "VK trusted term", "#a78bfa"),
    ("e(vk_x, gamma_2)", "public=\{num_public}", "#34d399"),
    ("e(pi_c, delta_2)", "C.x=\{pc_short}", "#f472b6"),
  ]
  for i = 0; i < 4; i = i + 1 {
    let x = 24 + i * 194
    let (title, sub, col) = terms[i]
    buf.write_string(
      "",
    )
    buf.write_string(
      "\{title}",
    )
    buf.write_string(
      "\{svg_escape(sub)}",
    )
  }

  buf.write_string(
    "",
  )
  buf.write_string(
    "Shared Final Exponentiation: prod_i e(P_i, Q_i) \{eq_sym}",
  )
  buf.write_string(
    "R1CS: \{num_constraints} constraints, \{num_wires} wires | pi_b.x0=\{svg_escape(pb_short)}",
  )
  buf.write_string("")
  buf.to_string()
}