///|
#derive(@debug.Debug)
pub(all) suberror ScpiError {
  PlanError(String)
  FrameError(String)
  TraceError(String)
  MeasurementError(String)
}

///|
pub fn ScpiError::message(self : ScpiError) -> String {
  match self {
    PlanError(message)
    | FrameError(message)
    | TraceError(message)
    | MeasurementError(message) => message
  }
}

///|
pub const MAX_TEXT_BYTES = 16384

///|
pub const MAX_BLOCK_BYTES = 1048576

///|
pub const MAX_CAPTURE_BYTES = 4194304

///|
#derive(Eq, @debug.Debug)
pub(all) enum Terminator {
  NoTerminator
  LF
  CRLF
}

///|
#derive(Eq, @debug.Debug)
pub(all) enum Mode {
  Text
  Block(Terminator)
}

///|
pub fn Mode::name(self : Mode) -> String {
  match self {
    Text => "text"
    Block(NoTerminator) => "block"
    Block(LF) => "block-lf"
    Block(CRLF) => "block-crlf"
  }
}

///|
pub fn Mode::from_name(name : String) -> Mode raise ScpiError {
  match name {
    "text" => Text
    "block" => Block(NoTerminator)
    "block-lf" => Block(LF)
    "block-crlf" => Block(CRLF)
    _ => raise TraceError("unknown response mode: " + name)
  }
}

///|
#derive(Eq, @debug.Debug)
pub(all) enum Response {
  Line(String)
  Binary(Bytes)
}

///|
pub struct Decoder {
  priv mode : Mode
  priv data : @buffer.Buffer
  priv mut next_line_byte : Int32
  priv mut body_start : Int32
  priv mut body_size : Int32?
  priv mut done : Bool
}

///|
pub fn Decoder::new(mode : Mode) -> Decoder {
  {
    mode,
    data: @buffer.Buffer(),
    next_line_byte: 0,
    body_start: 0,
    body_size: None,
    done: false,
  }
}

///|
fn ascii(bytes : ArrayView[Byte]) -> String raise ScpiError {
  let text = StringBuilder()
  for byte in bytes {
    let code = byte.to_int()
    guard code == 9 || (code >= 32 && code <= 126) else {
      raise FrameError("non-ASCII character in textual response")
    }
    text.write_char(code.unsafe_to_char())
  }
  text.to_string()
}

///|
fn Decoder::text(self : Decoder) -> Response? raise ScpiError {
  let bytes = self.data.view()
  for index in self.next_line_byte.. 0 && bytes[index - 1] == b'\r' {
        index - 1
      } else {
        index
      }
      guard last <= MAX_TEXT_BYTES else {
        raise FrameError("text response exceeds limit")
      }
      return Some(Line(ascii(bytes[:last])))
    }
  }
  self.next_line_byte = bytes.length()
  guard bytes.length() <= MAX_TEXT_BYTES + 1 else {
    raise FrameError("text response exceeds limit")
  }
  None
}

///|
fn suffix_bytes(suffix : Terminator) -> Bytes {
  match suffix {
    NoTerminator => b""
    LF => b"\n"
    CRLF => b"\r\n"
  }
}

///|
fn Decoder::block(
  self : Decoder,
  suffix : Terminator,
) -> Response? raise ScpiError {
  let bytes = self.data.view()
  if bytes.is_empty() {
    return None
  }
  guard bytes[0] == b'#' else {
    raise FrameError("expected IEEE 488.2 block marker #")
  }
  if self.body_size is None {
    if bytes.length() < 2 {
      return None
    }
    let digits = bytes[1].to_int() - 48
    guard digits >= 1 && digits <= 9 else {
      raise FrameError(
        "expected a definite-length block with 1..9 length digits",
      )
    }
    if bytes.length() < 2 + digits {
      return None
    }
    let mut size = 0
    for index in 2..<(2 + digits) {
      let digit = bytes[index].to_int() - 48
      guard digit >= 0 && digit <= 9 else {
        raise FrameError("invalid block length digit")
      }
      size = size * 10 + digit
      guard size <= MAX_BLOCK_BYTES else {
        raise FrameError("binary response exceeds limit")
      }
    }
    self.body_start = 2 + digits
    self.body_size = Some(size)
  }
  let end = self.body_start + self.body_size.unwrap()
  let terminator = suffix_bytes(suffix)
  let expected = end + terminator.length()
  guard bytes.length() <= expected else {
    raise FrameError("trailing bytes after the binary response")
  }
  if bytes.length() < end {
    return None
  }
  for index in end.. Response? raise ScpiError {
  guard !self.done else {
    raise FrameError("response decoder already finished")
  }
  let limit = match self.mode {
    Text => MAX_TEXT_BYTES + 2
    Block(_) => MAX_BLOCK_BYTES + 13
  }
  guard bytes.length() <= limit - self.data.length() else {
    raise FrameError("response exceeds byte limit")
  }
  self.data.write_bytesview(bytes)
  let response = match self.mode {
    Text => self.text()
    Block(suffix) => self.block(suffix)
  }
  self.done = response is Some(_)
  response
}

///|
pub fn Decoder::received(self : Decoder) -> Int32 {
  self.data.length()
}

///|
pub fn Decoder::wire(self : Decoder) -> Bytes {
  self.data.to_bytes()
}

///|
pub fn decode(mode : Mode, bytes : BytesView) -> Response raise ScpiError {
  guard Decoder::new(mode).feed(bytes) is Some(response) else {
    raise FrameError("truncated SCPI response")
  }
  response
}