///|
/// RESP2 / RESP3 协议值 ADT(四目标纯核)
#non_exhaustive
#derive(Debug, Eq)
pub(all) enum RespValue {
  SimpleString(String)
  SimpleError(String)
  BlobError(String)
  Integer(Int64)
  BigNumber(String)
  BulkString(Bytes)
  VerbatimString(encoding~ : String, data~ : Bytes)
  Null
  Array(Array[RespValue])
  Boolean(Bool)
  Double(Double)
  Map(Array[(RespValue, RespValue)])
  Set(Array[RespValue])
  Push(Array[RespValue])
}

///|
fn write_crlf(buf : Buffer) -> Unit {
  buf.write_byte(b'\r')
  buf.write_byte(b'\n')
}

///|
fn write_str(buf : Buffer, s : String) -> Unit {
  let b = @utf8.encode(s)
  buf.write_bytesview(b[:])
}

///|
/// 将命令参数列表编码为标准 RESP Bulk Array(如 `*2\r\n$3\r\nGET\r\n$3\r\nfoo\r\n`)
pub fn encode_command(args : Array[Bytes]) -> Bytes {
  let buf = Buffer()
  write_str(buf, "*\{args.length()}\r\n")
  for arg in args {
    write_str(buf, "$\{arg.length()}\r\n")
    buf.write_bytesview(arg[:])
    write_crlf(buf)
  }
  buf.to_bytes()
}

///|
/// 将任意 RespValue 编码为 RESP2/3 线格式字节流(用于客户端与 Mock Server 测试)
pub fn encode_value(value : RespValue) -> Bytes {
  let buf = Buffer()
  encode_value_into(buf, value)
  buf.to_bytes()
}

///|
fn encode_value_into(buf : Buffer, value : RespValue) -> Unit {
  match value {
    SimpleString(s) => {
      buf.write_byte(b'+')
      write_str(buf, s)
      write_crlf(buf)
    }
    SimpleError(s) => {
      buf.write_byte(b'-')
      write_str(buf, s)
      write_crlf(buf)
    }
    BlobError(s) => {
      let b = @utf8.encode(s)
      write_str(buf, "!\{b.length()}\r\n")
      buf.write_bytesview(b[:])
      write_crlf(buf)
    }
    Integer(n) => {
      buf.write_byte(b':')
      write_str(buf, n.to_string())
      write_crlf(buf)
    }
    BigNumber(s) => {
      buf.write_byte(b'(')
      write_str(buf, s)
      write_crlf(buf)
    }
    BulkString(b) => {
      write_str(buf, "$\{b.length()}\r\n")
      buf.write_bytesview(b[:])
      write_crlf(buf)
    }
    VerbatimString(encoding~, data~) => {
      let enc_bytes = @utf8.encode(encoding)
      let total_len = enc_bytes.length() + 1 + data.length()
      write_str(buf, "=\{total_len}\r\n")
      buf.write_bytesview(enc_bytes[:])
      buf.write_byte(b':')
      buf.write_bytesview(data[:])
      write_crlf(buf)
    }
    Null => write_str(buf, "_\r\n")
    Array(items) => {
      write_str(buf, "*\{items.length()}\r\n")
      for item in items {
        encode_value_into(buf, item)
      }
    }
    Boolean(b) => {
      buf.write_byte(b'#')
      buf.write_byte(if b { b't' } else { b'f' })
      write_crlf(buf)
    }
    Double(d) => {
      buf.write_byte(b',')
      write_str(buf, d.to_string())
      write_crlf(buf)
    }
    Map(entries) => {
      write_str(buf, "%\{entries.length()}\r\n")
      for pair in entries {
        encode_value_into(buf, pair.0)
        encode_value_into(buf, pair.1)
      }
    }
    Set(items) => {
      write_str(buf, "~\{items.length()}\r\n")
      for item in items {
        encode_value_into(buf, item)
      }
    }
    Push(items) => {
      write_str(buf, ">\{items.length()}\r\n")
      for item in items {
        encode_value_into(buf, item)
      }
    }
  }
}

///|
priv trait RespByteSource {
  fn byte_len(Self) -> Int32
  fn byte_at(Self, Int32) -> Byte
  fn slice_bytes(Self, Int32, Int32) -> Bytes
}

///|
impl RespByteSource for BytesView with fn byte_len(self) -> Int32 {
  self.length()
}

///|
impl RespByteSource for BytesView with fn byte_at(self, idx : Int32) -> Byte {
  self[idx]
}

///|
impl RespByteSource for BytesView with fn slice_bytes(
  self,
  start : Int32,
  end : Int32,
) -> Bytes {
  self[start:end].to_owned()
}

///|
impl RespByteSource for Array[Byte] with fn byte_len(self) -> Int32 {
  self.length()
}

///|
impl RespByteSource for Array[Byte] with fn byte_at(self, idx : Int32) -> Byte {
  self[idx]
}

///|
impl RespByteSource for Array[Byte] with fn slice_bytes(
  self,
  start : Int32,
  end : Int32,
) -> Bytes {
  Bytes::makei(end - start, i => self[start + i])
}

///|
fn[B : RespByteSource] find_crlf(buf : B, start : Int32) -> Int32? {
  let len = buf.byte_len()
  let mut i = start
  while i + 1 < len {
    if buf.byte_at(i) == b'\r' && buf.byte_at(i + 1) == b'\n' {
      return Some(i)
    }
    i = i + 1
  }
  None
}

///|
fn[B : RespByteSource] decode_utf8_slice(
  buf : B,
  start : Int32,
  end : Int32,
) -> String raise @codec.DataError {
  let bytes = buf.slice_bytes(start, end)
  @utf8.decode(bytes) catch {
    err =>
      raise @codec.DataError::ProtocolError(
        "invalid UTF-8 in RESP: \{Repr(err)}",
      )
  }
}

///|
fn[B : RespByteSource] parse_resp_at(
  buf : B,
  offset : Int32,
) -> (RespValue, Int32)? raise @codec.DataError {
  let buf_len = buf.byte_len()
  if offset >= buf_len {
    return None
  }
  let prefix = buf.byte_at(offset)
  let line_end = match find_crlf(buf, offset + 1) {
    Some(e) => e
    None => return None
  }
  let next = line_end + 2
  match prefix {
    b'+' => {
      let s = decode_utf8_slice(buf, offset + 1, line_end)
      Some((RespValue::SimpleString(s), next))
    }
    b'-' => {
      let s = decode_utf8_slice(buf, offset + 1, line_end)
      Some((RespValue::SimpleError(s), next))
    }
    b':' => {
      let s = decode_utf8_slice(buf, offset + 1, line_end)
      let n = @string.parse_int64(s) catch {
        _ =>
          raise @codec.DataError::ProtocolError("invalid RESP integer: '\{s}'")
      }
      Some((RespValue::Integer(n), next))
    }
    b'_' => Some((RespValue::Null, next))
    b'#' => {
      let s = decode_utf8_slice(buf, offset + 1, line_end)
      if s == "t" {
        Some((RespValue::Boolean(true), next))
      } else if s == "f" {
        Some((RespValue::Boolean(false), next))
      } else {
        raise @codec.DataError::ProtocolError("invalid RESP3 boolean: '\{s}'")
      }
    }
    b',' => {
      let s = decode_utf8_slice(buf, offset + 1, line_end)
      let d = @string.parse_double(s) catch {
        _ =>
          raise @codec.DataError::ProtocolError("invalid RESP3 double: '\{s}'")
      }
      Some((RespValue::Double(d), next))
    }
    b'$' => {
      let len_str = decode_utf8_slice(buf, offset + 1, line_end)
      let blen = @string.parse_int(len_str) catch {
        _ =>
          raise @codec.DataError::ProtocolError(
            "invalid RESP bulk length: '\{len_str}'",
          )
      }
      if blen < 0 {
        return Some((RespValue::Null, next))
      }
      if buf_len - next < 2 || blen > buf_len - next - 2 {
        return None
      }
      let end_pos = next + blen
      if buf.byte_at(end_pos) != b'\r' || buf.byte_at(end_pos + 1) != b'\n' {
        raise @codec.DataError::ProtocolError(
          "missing CRLF after RESP bulk string",
        )
      }
      let payload = buf.slice_bytes(next, end_pos)
      Some((RespValue::BulkString(payload), end_pos + 2))
    }
    b'*' | b'~' | b'>' => {
      let len_str = decode_utf8_slice(buf, offset + 1, line_end)
      let count = @string.parse_int(len_str) catch {
        _ =>
          raise @codec.DataError::ProtocolError(
            "invalid RESP aggregate length: '\{len_str}'",
          )
      }
      if count < 0 {
        return Some((RespValue::Null, next))
      }
      // Fast-fail incomplete frames before allocating: every RESP element is at least 3 bytes (e.g. `_\r\n`)
      let rem_bytes = buf_len - next
      if count > rem_bytes / 3 {
        return None
      }
      let cap = if count < 256 { count } else { 256 }
      let items : Array[RespValue] = Array(capacity=cap)
      let mut pos = next
      for _ in 0.. return None
          Some((v, np)) => {
            items.push(v)
            pos = np
          }
        }
      }
      let val = if prefix == b'*' {
        RespValue::Array(items)
      } else if prefix == b'~' {
        RespValue::Set(items)
      } else {
        RespValue::Push(items)
      }
      Some((val, pos))
    }
    b'%' => {
      let len_str = decode_utf8_slice(buf, offset + 1, line_end)
      let count = @string.parse_int(len_str) catch {
        _ =>
          raise @codec.DataError::ProtocolError(
            "invalid RESP3 map length: '\{len_str}'",
          )
      }
      if count < 0 {
        return Some((RespValue::Null, next))
      }
      // Fast-fail incomplete frames before allocating: every map entry is at least 6 bytes (key + value)
      let rem_bytes = buf_len - next
      if count > rem_bytes / 6 {
        return None
      }
      let cap = if count < 256 { count } else { 256 }
      let entries : Array[(RespValue, RespValue)] = Array(capacity=cap)
      let mut pos = next
      for _ in 0.. return None
          Some(r) => r
        }
        let (v, p2) = match parse_resp_at(buf, p1) {
          None => return None
          Some(r) => r
        }
        entries.push((k, v))
        pos = p2
      }
      Some((RespValue::Map(entries), pos))
    }
    b'(' => {
      let s = decode_utf8_slice(buf, offset + 1, line_end)
      if s.is_empty() {
        raise @codec.DataError::ProtocolError("empty RESP3 big number")
      }
      Some((RespValue::BigNumber(s), next))
    }
    b'!' => {
      let len_str = decode_utf8_slice(buf, offset + 1, line_end)
      let blen = @string.parse_int(len_str) catch {
        _ =>
          raise @codec.DataError::ProtocolError(
            "invalid RESP3 blob error length: '\{len_str}'",
          )
      }
      if blen < 0 {
        raise @codec.DataError::ProtocolError(
          "negative RESP3 blob error length",
        )
      }
      if buf_len - next < 2 || blen > buf_len - next - 2 {
        return None
      }
      let end_pos = next + blen
      if buf.byte_at(end_pos) != b'\r' || buf.byte_at(end_pos + 1) != b'\n' {
        raise @codec.DataError::ProtocolError(
          "missing CRLF after RESP3 blob error",
        )
      }
      let msg = decode_utf8_slice(buf, next, end_pos)
      Some((RespValue::BlobError(msg), end_pos + 2))
    }
    b'=' => {
      let len_str = decode_utf8_slice(buf, offset + 1, line_end)
      let blen = @string.parse_int(len_str) catch {
        _ =>
          raise @codec.DataError::ProtocolError(
            "invalid RESP3 verbatim string length: '\{len_str}'",
          )
      }
      if blen < 4 {
        raise @codec.DataError::ProtocolError(
          "RESP3 verbatim string must be at least 4 bytes (enc:)",
        )
      }
      if buf_len - next < 2 || blen > buf_len - next - 2 {
        return None
      }
      let end_pos = next + blen
      if buf.byte_at(end_pos) != b'\r' || buf.byte_at(end_pos + 1) != b'\n' {
        raise @codec.DataError::ProtocolError(
          "missing CRLF after RESP3 verbatim string",
        )
      }
      if buf.byte_at(next + 3) != b':' {
        raise @codec.DataError::ProtocolError(
          "missing ':' delimiter in RESP3 verbatim string",
        )
      }
      let encoding = decode_utf8_slice(buf, next, next + 3)
      let data = buf.slice_bytes(next + 4, end_pos)
      Some((RespValue::VerbatimString(encoding~, data~), end_pos + 2))
    }
    b'|' => {
      // RESP3 Attribute frame: `|\r\n` followed by `count` key-value pairs and then the primary reply frame
      let len_str = decode_utf8_slice(buf, offset + 1, line_end)
      let count = @string.parse_int(len_str) catch {
        _ =>
          raise @codec.DataError::ProtocolError(
            "invalid RESP3 attribute length: '\{len_str}'",
          )
      }
      if count < 0 {
        raise @codec.DataError::ProtocolError("negative RESP3 attribute length")
      }
      let mut pos = next
      for _ in 0.. return None
          Some(r) => r
        }
        let (_v, p2) = match parse_resp_at(buf, p1) {
          None => return None
          Some(r) => r
        }
        pos = p2
      }
      // Transparently parse and return the attached main value frame
      parse_resp_at(buf, pos)
    }
    _ =>
      raise @codec.DataError::ProtocolError(
        "unexpected RESP prefix byte: \{prefix.to_int()}",
      )
  }
}

///|
/// 增量解码单帧 RESP2/3 值:字节不足返回 None,成功返回 Some((值, 消费字节数))
pub fn decode_resp(
  buf : BytesView,
) -> (RespValue, Int32)? raise @codec.DataError {
  parse_resp_at(buf, 0)
}

///|
/// 流式增量 RESP 解码器(游标缓冲 + 均摊 O(N) 原地压缩,消除大 Pipeline 的 O(N^2) 字节拷贝)
pub struct RespDecoder {
  priv buf : Array[Byte]
  priv mut head : Int32
}

///|
pub fn RespDecoder::RespDecoder() -> RespDecoder {
  { buf: [], head: 0, }
}

///|
pub fn RespDecoder::feed(self : RespDecoder, chunk : BytesView) -> Unit {
  if chunk.is_empty() {
    return
  }
  if self.head >= self.buf.length() {
    self.buf.clear()
    self.head = 0
  }
  for i in 0.. RespValue? raise @codec.DataError {
  let len = self.buf.length()
  if self.head >= len {
    return None
  }
  match parse_resp_at(self.buf, self.head) {
    None => None
    Some((val, next_pos)) => {
      self.head = next_pos
      if self.head >= len {
        self.buf.clear()
        self.head = 0
      } else if self.head > 4096 && self.head >= len - self.head {
        let rem = len - self.head
        for i in 0..