///|
pub struct Client {
  transport : RedisTransport
  /// Buffered read window over `conn`; bytes read past the current reply stay
  /// buffered instead of being dropped mid-frame.
  priv mut read_buf : FixedArray[Byte]
  /// Offset of the first unconsumed byte inside `read_buf`.
  priv mut read_start : Int32
  /// Offset one past the last valid byte inside `read_buf`.
  priv mut read_end : Int32
  /// Scan cursor used to look for the next line terminator; always within
  /// `[read_start, read_end)`.
  priv mut read_scan : Int32
}

///|

///|
pub impl RedisHost for StringView with fn memory_backend(_) {
  None
}

///|
pub impl RedisHost for StringView with fn hostname(self) {
  self
}

///|
pub impl RedisHost for String with fn memory_backend(_) {
  None
}

///|
pub impl RedisHost for String with fn hostname(self) {
  self[:]
}

///|
/// 连接建立过程中的错误
pub(all) suberror ConnectError {
  /// AUTH 认证失败
  AuthFailed(String)
  /// SELECT 选择数据库失败
  SelectFailed(String)
}

///|
#deprecated("Use `@redis.Client` instead of `@redis.Client` to create a RedisClient.")
pub async fn connect(
  host : StringView,
  port~ : Int32 = 6379,
  protocol? : @socket.IpProtocolPreference,
  username? : String,
  password? : String,
  db? : Int32,
) -> Client {
  Client(host, port~, protocol?, username?, password?, db?)
}

///|
/// 建立到 Redis 服务器的连接。
///
/// 连接建立后可选地自动完成认证和选库:
/// - `password?`:提供时自动发送 AUTH;
///   同时提供 `username?` 时使用 Redis 6+ ACL 形式 `AUTH  `。
///   单独提供 `username?` 而不提供 `password?` 时不发送 AUTH(Redis 没有仅用户名的认证)。
/// - `db?`:提供时自动发送 `SELECT ` 切换到指定数据库。
///
/// 认证或选库失败时会关闭连接并抛出 `ConnectError`。
pub async fn Client::Client(
  host : &RedisHost,
  port~ : Int32 = 6379,
  protocol? : @socket.IpProtocolPreference,
  username? : String,
  password? : String,
  db? : Int32,
) -> Client {
  let transport = match host.memory_backend() {
    Some(backend) => RedisTransport::Memory(backend)
    None => {
      let conn = @socket.Tcp::connect_to_host(host.hostname(), port~, protocol?)
      conn.enable_keepalive()
      RedisTransport::Network(conn)
    }
  }
  let client = Client::from_transport(transport)
  if password is Some(password) {
    let args = match username {
      Some(username) => ["AUTH", username, password]
      None => ["AUTH", password]
    }
    match client.send(args) {
      SimpleString("OK") => ()
      Error(e) => {
        client.close()
        raise AuthFailed(e)
      }
      resp => {
        client.close()
        raise AuthFailed("unexpected response: \{resp}")
      }
    }
  }
  if db is Some(db) {
    match client.send(["SELECT", db.to_string()]) {
      SimpleString("OK") => ()
      Error(e) => {
        client.close()
        raise SelectFailed(e)
      }
      resp => {
        client.close()
        raise SelectFailed("unexpected response: \{resp}")
      }
    }
  }
  client
}

///|
fn Client::from_transport(transport : RedisTransport) -> Client {
  {
    transport,
    read_buf: FixedArray::make(READ_CHUNK, b'\x00'),
    read_start: 0,
    read_end: 0,
    read_scan: 0,
  }
}

///|
/// Build a Redis client directly on an in-memory Redis backend.
/// This is intended for tests: commands execute locally and no TCP socket is
/// created.
pub fn[T : RedisMemoryBackend] Client::memory(
  backend : T,
  username? : String,
  password? : String,
  db? : Int32,
) -> Client raise ConnectError {
  let client : Client = {
    transport: RedisTransport::Memory(backend as &RedisMemoryBackend),
    read_buf: FixedArray::make(READ_CHUNK, b'\x00'),
    read_start: 0,
    read_end: 0,
    read_scan: 0,
  }
  if password is Some(password) {
    let args = match username {
      Some(username) => ["AUTH", username, password]
      None => ["AUTH", password]
    }
    match client.send_sync(args) {
      SimpleString("OK") => ()
      Error(e) => raise AuthFailed(e)
      resp => raise AuthFailed("unexpected response: \{resp}")
    }
  }
  if db is Some(db) {
    match client.send_sync(["SELECT", db.to_string()]) {
      SimpleString("OK") => ()
      Error(e) => raise SelectFailed(e)
      resp => raise SelectFailed("unexpected response: \{resp}")
    }
  }
  client
}

///|
fn Client::send_sync(self : Client, args : Array[String]) -> RedisValue {
  match self.transport {
    RedisTransport::Memory(backend) => backend.execute(args)
    RedisTransport::Network(_) => Error("send_sync called on network client")
  }
}

///|
pub async fn Client::send(self : Client, args : Array[String]) -> RedisValue {
  match self.transport {
    RedisTransport::Memory(backend) => return backend.execute(args)
    RedisTransport::Network(_) => ()
  }
  let total = frame_length(args)
  let buf = FixedArray::make(total, b'\x00')
  encode_frame(args, buf)
  match self.transport {
    RedisTransport::Network(conn) =>
      conn.write(buf.unsafe_reinterpret_as_bytes()[0:total])
    RedisTransport::Memory(_) => ()
  }
  self.read_redis_value()
}

///|
const READ_CHUNK : Int32 = 16384

///|
/// Read exactly one RESP2 reply: take the header line from the stream, then read a
/// bulk body by its declared byte length instead of "whatever one socket read
/// happens to return".
async fn Client::read_value(self : Client) -> RedisValue {
  match self.read_line() {
    None => Error("Connection closed")
    Some((body_start, body_len)) => {
      let tag = self.read_buf[body_start - 1]
      match tag {
        b'+' => SimpleString(self.decode_body(body_start, body_len))
        b'-' => Error(self.decode_body(body_start, body_len))
        b':' =>
          match self.parse_body_int(body_start, body_len) {
            Some(number) => Integer(number)
            None => Error("Invalid integer")
          }
        b'$' => self.read_bulk(body_start, body_len)
        b'*' => self.read_array(body_start, body_len)
        _ => Error("Unknown response type")
      }
    }
  }
}

///|
/// Decode `len` bytes of the current line body into a string.
fn Client::decode_body(self : Client, start : Int32, len : Int32) -> String {
  decode_span(self.read_buf.unsafe_reinterpret_as_bytes(), start, start + len)
}

///|
/// Parse the current line body as a decimal integer, without allocating.
fn Client::parse_body_int(self : Client, start : Int32, len : Int32) -> Int32? {
  parse_int_bytes(
    self.read_buf.unsafe_reinterpret_as_bytes(),
    start,
    start + len,
  )
}

///|
/// Read one CRLF-terminated line from the buffer, pulling more bytes from the
/// socket as needed.
///
/// Returns the buffer offset of the line body and its length, with the tag byte
/// and the terminator excluded. The line is consumed, so the next reply starts
/// at the current cursor. The body bytes stay in the buffer until the next
/// compaction, so callers must read them before issuing another read.
///
/// A bare "\n" terminator is tolerated the way redis-cli handles interactive
/// replies; regular Redis replies always end with CRLF.
async fn Client::read_line(self : Client) -> (Int32, Int32)? {
  while true {
    let mut i = self.read_scan
    while i < self.read_end {
      let b = self.read_buf[i]
      if b == b'\r' {
        if i + 1 < self.read_end {
          if self.read_buf[i + 1] == b'\n' {
            return Some(self.take_line(i, 2))
          }
          // "\r" mid-line without "\n": keep scanning for the real terminator.
          i += 1
          continue
        }
        // The "\r" may be the last buffered byte; wait for the next byte.
        break
      } else if b == b'\n' {
        return Some(self.take_line(i, 1))
      }
      i += 1
    }
    self.read_scan = i
    // No terminator in the window yet: fetch more bytes.
    if self.fill() == 0 {
      if self.read_end > self.read_start {
        // EOF without a terminator: return what is left as one line.
        return Some(self.take_line(self.read_end, 0))
      }
      return None
    }
  }
  None
}

///|
/// Take the line whose body ends at `body_end` (exclusive) and whose
/// terminator is `terminator_len` bytes long, consume the whole line, and
/// return the offset and length of its body.
fn Client::take_line(
  self : Client,
  body_end : Int32,
  terminator_len : Int32,
) -> (Int32, Int32) {
  let body_start = self.read_start + 1
  let body_len = body_end - body_start
  self.consume(body_end - self.read_start + terminator_len)
  (body_start, body_len)
}

///|
/// Consume `len` bytes of the buffer, making room for the next reply.
fn Client::consume(self : Client, len : Int32) -> Unit {
  self.read_start += len
  if self.read_start >= self.read_end {
    // Fully drained: rewind to the start of the buffer.
    self.read_start = 0
    self.read_end = 0
    self.read_scan = 0
  } else {
    self.read_scan = self.read_start
  }
}

///|
/// Pull more bytes from the socket into the buffer's free space, compacting or
/// growing the buffer when needed. Returns the number of bytes read; 0 marks EOF.
async fn Client::fill(self : Client) -> Int32 {
  if self.read_start == self.read_end {
    // Fully drained: rewind to the start of the buffer.
    self.read_start = 0
    self.read_end = 0
    self.read_scan = 0
  } else if self.read_end == self.read_buf.length() {
    if self.read_start > 0 {
      // Compact the unconsumed bytes to the front of the buffer.
      self.read_buf.unsafe_blit(
        0,
        self.read_buf,
        self.read_start,
        self.read_end - self.read_start,
      )
      self.read_end -= self.read_start
      self.read_scan -= self.read_start
      self.read_start = 0
    } else {
      // The buffer is full of unconsumed data: grow it.
      let bigger = FixedArray::make(self.read_buf.length() * 2, b'\x00')
      self.read_buf.blit_to(bigger, len=self.read_end)
      self.read_buf = bigger
    }
  }
  let n = match self.transport {
    RedisTransport::Network(conn) =>
      conn.read(
        self.read_buf,
        offset=self.read_end,
        max_len=self.read_buf.length() - self.read_end,
      )
    RedisTransport::Memory(_) => 0
  }
  if n > 0 {
    self.read_end += n
  }
  n
}

///|
/// Ensure at least `len` unconsumed bytes are buffered. Returns the buffer
/// offset of that slice, or `None` at EOF.
async fn Client::read_exact(self : Client, len : Int32) -> Int32? {
  while true {
    if self.read_end - self.read_start >= len {
      return Some(self.read_start)
    }
    if self.fill() == 0 {
      return None
    }
  }
  None
}

///|
/// Read a bulk body: `$-1` is an absent value, otherwise exactly `len` bytes plus
/// the trailing CRLF.
async fn Client::read_bulk(
  self : Client,
  len_start : Int32,
  len_len : Int32,
) -> RedisValue {
  match self.parse_body_int(len_start, len_len) {
    None => Error("Invalid bulk length")
    Some(len) =>
      if len < 0 {
        BulkString(None)
      } else {
        match self.read_exact(len + 2) {
          None => Error("Connection closed while reading bulk reply")
          Some(payload_start) => {
            let payload = decode_span(
              self.read_buf.unsafe_reinterpret_as_bytes(),
              payload_start,
              payload_start + len,
            )
            self.consume(len + 2)
            BulkString(Some(payload))
          }
        }
      }
  }
}

///|
/// Read `count` nested replies, each framed on its own.
async fn Client::read_array(
  self : Client,
  count_start : Int32,
  count_len : Int32,
) -> RedisValue {
  match self.parse_body_int(count_start, count_len) {
    None => Error("Invalid array count")
    Some(count) =>
      if count < 0 {
        Array([])
      } else {
        let items : Array[RedisValue] = Array(capacity=count)
        for _ in 0.. String {
  let value = self.read_value()
  match value {
    SimpleString(text) | BulkString(Some(text)) => text
    BulkString(None) => ""
    Integer(number) => number.to_string()
    Error(message) => "ERR " + message
    Array(items) => items.map(item => item.to_array_item_string()).join(" ")
  }
}

///|
/// 读取Redis响应并解析为RedisValue类型
pub async fn Client::read_redis_value(self : Client) -> RedisValue {
  self.read_value()
}

///|
pub async fn Client::write(self : Client, data : String) -> Unit {
  match self.transport {
    RedisTransport::Network(conn) => conn.write(data)
    RedisTransport::Memory(_) => ()
  }
}

///|
pub async fn Client::read(self : Client, buf : FixedArray[Byte]) -> Int32 {
  match self.transport {
    RedisTransport::Memory(_) => return 0
    RedisTransport::Network(_) => ()
  }
  if self.read_start == self.read_end {
    match self.transport {
      RedisTransport::Network(conn) => return conn.read(buf)
      RedisTransport::Memory(_) => return 0
    }
  }
  // Serve the buffered bytes first, then the socket.
  let n = (self.read_end - self.read_start).min(buf.length())
  self.read_buf.blit_to(buf, len=n, src_offset=self.read_start)
  self.consume(n)
  n
}

///|
pub fn Client::close(self : Client) -> Unit {
  match self.transport {
    RedisTransport::Network(conn) => conn.close()
    RedisTransport::Memory(_) => ()
  }
}