///|
pub(all) struct Exchange {
  request : Request
  bytes : Bytes
}

///|
pub(all) struct Trace {
  exchanges : Array[Exchange]
  failure : String?
}

///|
fn hex_digit(digit : Int32) -> Char {
  (digit + (if digit < 10 { 48 } else { 87 })).unsafe_to_char()
}

///|
fn hex_encode(data : Bytes) -> String {
  let output = StringBuilder(capacity=data.length() * 2)
  for byte in data {
    let value = byte.to_int()
    output.write_char(hex_digit(value >> 4))
    output.write_char(hex_digit(value & 15))
  }
  output.to_string()
}

///|
fn hex_decode(text : String, limit : Int32) -> Bytes raise ScpiError {
  guard text.length() % 2 == 0 && text.length() / 2 <= limit else {
    raise TraceError("invalid trace byte count")
  }
  let output = @buffer.Buffer(capacity=text.length() / 2)
  let mut high = -1
  for char in text {
    let digit = match char {
      '0'..<='9' => char.to_int() - 48
      'a'..<='f' => char.to_int() - 87
      'A'..<='F' => char.to_int() - 55
      _ => raise TraceError("invalid hexadecimal trace payload")
    }
    if high == -1 {
      high = digit
    } else {
      output.write_byte((high * 16 + digit).to_byte())
      high = -1
    }
  }
  output.to_bytes()
}

///|
pub fn Trace::to_json(self : Trace) -> Json {
  let entries = self.exchanges.map(exchange => {
    Json::object(
      Map([
        ("query", Json(exchange.request.query)),
        ("mode", Json(exchange.request.mode.name())),
        ("wire_hex", Json(hex_encode(exchange.bytes))),
      ]),
    )
  })
  Json::object(
    Map([
      ("format", Json("moonscpi-trace-v1")),
      ("exchanges", Json::array(entries)),
      ("failure", self.failure.map(s => Json(s)).unwrap_or(Json::null())),
    ]),
  )
}

///|
pub fn Trace::parse(text : StringView) -> Trace raise ScpiError {
  let value = @json.parse(text, reject_duplicate_keys=true) catch {
    error => raise TraceError(error.to_string())
  }
  guard value is Object(fields) &&
    fields.length() == 3 &&
    fields.get("format") is Some(String("moonscpi-trace-v1")) &&
    fields.get("exchanges") is Some(Array(entries)) &&
    entries.length() <= 256 else {
    raise TraceError("invalid trace v1 envelope")
  }
  let failure = match fields.get("failure") {
    Some(Null) => None
    Some(String(text)) if !text.is_empty() && text.length() <= 4096 =>
      Some(text)
    _ => raise TraceError("trace failure must be null or a short diagnostic")
  }
  let exchanges = []
  let mut remaining = MAX_CAPTURE_BYTES
  for value in entries {
    guard value is Object(entry) &&
      entry.length() == 3 &&
      entry.get("query") is Some(String(query)) &&
      query.length() <= 240 &&
      entry.get("mode") is Some(String(mode)) &&
      entry.get("wire_hex") is Some(String(data)) else {
      raise TraceError("invalid trace exchange")
    }
    let bytes = hex_decode(data, remaining)
    remaining -= bytes.length()
    exchanges.push({ request: { query, mode: Mode::from_name(mode), }, bytes, })
  }
  { exchanges, failure, }
}

///|
fn Plan::verify_trace(self : Plan, trace : Trace) -> Unit raise ScpiError {
  let expected = self.requests()
  guard trace.exchanges.length() <= expected.length() &&
    (trace.failure is Some(_) || trace.exchanges.length() == expected.length()) else {
    raise TraceError("trace record count does not match the selected plan")
  }
  let mut remaining = MAX_CAPTURE_BYTES
  for index, entry in trace.exchanges {
    guard entry.request == expected[index] else {
      raise TraceError(
        "trace request mismatch at query " + (index + 1).to_string(),
      )
    }
    remaining -= entry.bytes.length()
    guard remaining >= 0 else {
      raise TraceError("trace exceeds capture limit")
    }
  }
}