///|
/// PostgreSQL Frontend/Backend Protocol v3.0 message codecs and incremental frame decoder.
/// Four-target pure package (+native+js+wasm+wasm-gc) with zero async or I/O dependencies.

///|
pub let pg_protocol_version : Int32 = 196608 // (3 << 16) | 0

///|
pub let pg_ssl_request_code : Int32 = 80877103 // (1234 << 16) | 5679

///|
pub let pg_cancel_request_code : Int32 = 80877102 // (1234 << 16) | 5678

///|
#derive(Debug, Eq)
pub(all) struct FieldDesc {
  name : String
  table_oid : Int32
  column_attr : Int32
  type_oid : Int32
  type_size : Int32
  type_modifier : Int32
  format_code : Int32
}

///|
#derive(Debug, Eq)
pub(all) struct PgErrorFields {
  severity : String
  code : String
  message : String
  detail : String?
  constraint : String?
  table : String?
}

///|
#non_exhaustive
#derive(Debug, Eq)
pub(all) enum AuthRequest {
  Ok
  CleartextPassword
  Md5Password(Bytes)
  Sasl(Array[String])
  SaslContinue(Bytes)
  SaslFinal(Bytes)
  Unsupported(Int32)
}

///|
#non_exhaustive
#derive(Debug, Eq)
pub(all) enum BackendMessage {
  Authentication(AuthRequest)
  BackendKeyData(process_id~ : Int32, secret_key~ : Int32)
  ParameterStatus(name~ : String, value~ : String)
  ReadyForQuery(status~ : Byte)
  ParseComplete
  BindComplete
  CloseComplete
  EmptyQueryResponse
  NoData
  ParameterDescription(Array[Int32])
  RowDescription(Array[FieldDesc])
  DataRow(Array[Bytes?])
  CommandComplete(String)
  ErrorResponse(PgErrorFields)
  NoticeResponse(PgErrorFields)
  PortalSuspended
  Unknown(tag~ : Byte, payload~ : Bytes)
}

///|
fn write_i32_be(buf : Array[Byte], v : Int32) -> Unit {
  buf.push(((v >> 24) & 0xFF).to_byte())
  buf.push(((v >> 16) & 0xFF).to_byte())
  buf.push(((v >> 8) & 0xFF).to_byte())
  buf.push((v & 0xFF).to_byte())
}

///|
fn write_i16_be(buf : Array[Byte], v : Int32) -> Unit {
  buf.push(((v >> 8) & 0xFF).to_byte())
  buf.push((v & 0xFF).to_byte())
}

///|
fn write_cstr(buf : Array[Byte], s : StringView) -> Unit {
  let bytes = @utf8.encode(s)
  for b in bytes {
    buf.push(b)
  }
  buf.push(b'\x00')
}

///|
fn write_bytes_all(buf : Array[Byte], data : BytesView) -> Unit {
  for b in data {
    buf.push(b)
  }
}

///|
fn read_i32_be(data : BytesView, pos : Int32) -> Int32 {
  let b0 = data[pos].to_int()
  let b1 = data[pos + 1].to_int()
  let b2 = data[pos + 2].to_int()
  let b3 = data[pos + 3].to_int()
  (b0 << 24) | (b1 << 16) | (b2 << 8) | b3
}

///|
fn read_i16_be(data : BytesView, pos : Int32) -> Int32 {
  let b0 = data[pos].to_int()
  let b1 = data[pos + 1].to_int()
  let raw = (b0 << 8) | b1
  if raw >= 32768 {
    raw - 65536
  } else {
    raw
  }
}

///|
fn read_cstr(
  data : BytesView,
  pos : Int32,
) -> (String, Int32) raise @codec.DataError {
  let n = data.length()
  let mut end = pos
  while end < n && data[end] != b'\x00' {
    end += 1
  }
  if end >= n {
    raise @codec.DataError::ProtocolError("unterminated C-string in PG message")
  }
  let s = @utf8.decode(data[pos:end]) catch {
    _ => raise @codec.DataError::ProtocolError("invalid UTF-8 in PG C-string")
  }
  (s, end + 1)
}

///|
fn frame_tagged(tag : Byte, payload : Array[Byte]) -> Bytes {
  let out : Array[Byte] = []
  out.push(tag)
  write_i32_be(out, payload.length() + 4)
  for b in payload {
    out.push(b)
  }
  Bytes::from_array(out)
}

///|
/// Encodes a PostgreSQL v3 `StartupMessage` (no leading type byte).
pub fn encode_startup(
  user~ : String,
  database~ : String,
  params~ : Array[(String, String)] = [],
) -> Bytes {
  let body : Array[Byte] = []
  write_i32_be(body, pg_protocol_version)
  write_cstr(body, "user")
  write_cstr(body, user)
  write_cstr(body, "database")
  write_cstr(body, database)
  write_cstr(body, "client_encoding")
  write_cstr(body, "UTF8")
  for pair in params {
    write_cstr(body, pair.0)
    write_cstr(body, pair.1)
  }
  body.push(b'\x00')
  let out : Array[Byte] = []
  write_i32_be(out, body.length() + 4)
  for b in body {
    out.push(b)
  }
  Bytes::from_array(out)
}

///|
/// Encodes a PostgreSQL `SSLRequest` negotiation packet (8 bytes).
pub fn encode_ssl_request() -> Bytes {
  let out : Array[Byte] = []
  write_i32_be(out, 8)
  write_i32_be(out, pg_ssl_request_code)
  Bytes::from_array(out)
}

///|
/// Encodes a PostgreSQL `CancelRequest` packet (16 bytes, code `80877102`).
pub fn encode_cancel_request(process_id~ : Int32, secret_key~ : Int32) -> Bytes {
  let out : Array[Byte] = []
  write_i32_be(out, 16)
  write_i32_be(out, pg_cancel_request_code)
  write_i32_be(out, process_id)
  write_i32_be(out, secret_key)
  Bytes::from_array(out)
}

///|
/// Encodes a `PasswordMessage` (`'p'`) for cleartext or MD5 authentication.
pub fn encode_password_message(password : StringView) -> Bytes {
  let body : Array[Byte] = []
  write_cstr(body, password)
  frame_tagged(b'p', body)
}

///|
/// Encodes a `SASLInitialResponse` (`'p'`) message for SCRAM-SHA-256.
pub fn encode_sasl_initial_response(
  mechanism : StringView,
  initial_data : BytesView,
) -> Bytes {
  let body : Array[Byte] = []
  write_cstr(body, mechanism)
  if initial_data.length() == 0 {
    write_i32_be(body, -1)
  } else {
    write_i32_be(body, initial_data.length())
    write_bytes_all(body, initial_data)
  }
  frame_tagged(b'p', body)
}

///|
/// Encodes a `SASLResponse` (`'p'`) message carrying client-final-message.
pub fn encode_sasl_response(data : BytesView) -> Bytes {
  let body : Array[Byte] = []
  write_bytes_all(body, data)
  frame_tagged(b'p', body)
}

///|
/// Encodes a Simple Query (`'Q'`) message.
pub fn encode_simple_query(sql : StringView) -> Bytes {
  let body : Array[Byte] = []
  write_cstr(body, sql)
  frame_tagged(b'Q', body)
}

///|
/// Encodes an Extended Query `Parse` (`'P'`) message.
pub fn encode_parse(
  stmt_name~ : String,
  sql~ : String,
  param_oids~ : Array[Int32] = [],
) -> Bytes {
  let body : Array[Byte] = []
  write_cstr(body, stmt_name)
  write_cstr(body, sql)
  write_i16_be(body, param_oids.length())
  for oid in param_oids {
    write_i32_be(body, oid)
  }
  frame_tagged(b'P', body)
}

///|
/// Encodes an Extended Query `Bind` (`'B'`) message using text parameter & result format codes.
pub fn encode_bind(
  portal_name~ : String,
  stmt_name~ : String,
  params~ : Array[Bytes?],
) -> Bytes {
  let body : Array[Byte] = []
  write_cstr(body, portal_name)
  write_cstr(body, stmt_name)
  // Parameter format codes: 0 entries -> all text format (0)
  write_i16_be(body, 0)
  write_i16_be(body, params.length())
  for p in params {
    match p {
      None => write_i32_be(body, -1)
      Some(b) => {
        write_i32_be(body, b.length())
        write_bytes_all(body, b[:])
      }
    }
  }
  // Result column format codes: 0 entries -> all text format (0)
  write_i16_be(body, 0)
  frame_tagged(b'B', body)
}

///|
/// Encodes an Extended Query `Describe` (`'D'`) message (`target`: `b'S'` for Statement or `b'P'` for Portal).
pub fn encode_describe(target~ : Byte, name~ : String) -> Bytes {
  let body : Array[Byte] = []
  body.push(target)
  write_cstr(body, name)
  frame_tagged(b'D', body)
}

///|
/// Encodes an Extended Query `Execute` (`'E'`) message (`max_rows = 0` means unlimited).
pub fn encode_execute(portal_name~ : String, max_rows~ : Int32 = 0) -> Bytes {
  let body : Array[Byte] = []
  write_cstr(body, portal_name)
  write_i32_be(body, max_rows)
  frame_tagged(b'E', body)
}

///|
/// Encodes an Extended Query `Close` (`'C'`) message (`target`: `b'S'` or `b'P'`).
pub fn encode_close(target~ : Byte, name~ : String) -> Bytes {
  let body : Array[Byte] = []
  body.push(target)
  write_cstr(body, name)
  frame_tagged(b'C', body)
}

///|
/// Encodes a `Sync` (`'S'`) message.
pub fn encode_sync() -> Bytes {
  frame_tagged(b'S', [])
}

///|
/// Encodes a `Terminate` (`'X'`) message.
pub fn encode_terminate() -> Bytes {
  frame_tagged(b'X', [])
}

///|
fn parse_error_fields(
  payload : BytesView,
) -> PgErrorFields raise @codec.DataError {
  let mut severity = ""
  let mut code = ""
  let mut message = ""
  let mut detail : String? = None
  let mut constraint : String? = None
  let mut table : String? = None
  let mut pos = 0
  let n = payload.length()
  while pos < n {
    let field_type = payload[pos]
    pos += 1
    if field_type == b'\x00' {
      break
    }
    let (val, next_pos) = read_cstr(payload, pos)
    pos = next_pos
    match field_type {
      b'S' | b'V' =>
        if severity.is_empty() || field_type == b'V' {
          severity = val
        }
      b'C' => code = val
      b'M' => message = val
      b'D' => detail = Some(val)
      b'n' => constraint = Some(val)
      b't' => table = Some(val)
      _ => ()
    }
  }
  { severity, code, message, detail, constraint, table, }
}

///|
fn parse_auth_message(
  payload : BytesView,
) -> BackendMessage raise @codec.DataError {
  if payload.length() < 4 {
    raise @codec.DataError::ProtocolError("truncated Authentication message")
  }
  let code = read_i32_be(payload, 0)
  match code {
    0 => BackendMessage::Authentication(AuthRequest::Ok)
    3 => BackendMessage::Authentication(AuthRequest::CleartextPassword)
    5 => {
      if payload.length() < 8 {
        raise @codec.DataError::ProtocolError("truncated MD5 salt")
      }
      BackendMessage::Authentication(
        AuthRequest::Md5Password(payload[4:8].to_owned()),
      )
    }
    10 => {
      let mechs : Array[String] = []
      let mut pos = 4
      while pos < payload.length() && payload[pos] != b'\x00' {
        let (m, next_pos) = read_cstr(payload, pos)
        mechs.push(m)
        pos = next_pos
      }
      BackendMessage::Authentication(AuthRequest::Sasl(mechs))
    }
    11 =>
      BackendMessage::Authentication(
        AuthRequest::SaslContinue(payload[4:].to_owned()),
      )
    12 =>
      BackendMessage::Authentication(
        AuthRequest::SaslFinal(payload[4:].to_owned()),
      )
    other => BackendMessage::Authentication(AuthRequest::Unsupported(other))
  }
}

///|
fn parse_row_description(
  payload : BytesView,
) -> BackendMessage raise @codec.DataError {
  if payload.length() < 2 {
    raise @codec.DataError::ProtocolError("truncated RowDescription")
  }
  let count = read_i16_be(payload, 0)
  if count < 0 {
    raise @codec.DataError::ProtocolError("negative RowDescription field count")
  }
  let fields : Array[FieldDesc] = []
  let mut pos = 2
  for _ in 0.. payload.length() {
      raise @codec.DataError::ProtocolError("truncated RowDescription entry")
    }
    let table_oid = read_i32_be(payload, pos)
    let column_attr = read_i16_be(payload, pos + 4)
    let type_oid = read_i32_be(payload, pos + 6)
    let type_size = read_i16_be(payload, pos + 10)
    let type_modifier = read_i32_be(payload, pos + 12)
    let format_code = read_i16_be(payload, pos + 16)
    pos += 18
    fields.push({
      name,
      table_oid,
      column_attr,
      type_oid,
      type_size,
      type_modifier,
      format_code,
    })
  }
  BackendMessage::RowDescription(fields)
}

///|
fn parse_data_row(payload : BytesView) -> BackendMessage raise @codec.DataError {
  if payload.length() < 2 {
    raise @codec.DataError::ProtocolError("truncated DataRow")
  }
  let count = read_i16_be(payload, 0)
  if count < 0 {
    raise @codec.DataError::ProtocolError("negative DataRow column count")
  }
  let cols : Array[Bytes?] = []
  let mut pos = 2
  for _ in 0.. payload.length() {
      raise @codec.DataError::ProtocolError("truncated DataRow column length")
    }
    let len = read_i32_be(payload, pos)
    pos += 4
    if len == -1 {
      cols.push(None)
    } else if len < 0 || len > payload.length() - pos {
      raise @codec.DataError::ProtocolError("invalid DataRow column length")
    } else {
      cols.push(Some(payload[pos:pos + len].to_owned()))
      pos += len
    }
  }
  BackendMessage::DataRow(cols)
}

///|
const MAX_PG_MESSAGE_LEN : Int32 = 67_108_864

///|
/// Decodes one complete PostgreSQL backend message from `buf`, returning `(message, bytes_consumed)`.
/// Returns `None` if more bytes are needed.
pub fn decode_backend_message(
  buf : BytesView,
) -> (BackendMessage, Int32)? raise @codec.DataError {
  if buf.length() < 5 {
    return None
  }
  let tag = buf[0]
  let msg_len = read_i32_be(buf, 1)
  if msg_len < 4 || msg_len > MAX_PG_MESSAGE_LEN {
    raise @codec.DataError::ProtocolError(
      "invalid PG message length: \{msg_len}",
    )
  }
  if buf.length() - 1 < msg_len {
    return None
  }
  let total_len = 1 + msg_len
  let payload = buf[5:total_len]
  let msg : BackendMessage = match tag {
    b'R' => parse_auth_message(payload)
    b'K' => {
      if payload.length() < 8 {
        raise @codec.DataError::ProtocolError("truncated BackendKeyData")
      }
      BackendMessage::BackendKeyData(
        process_id=read_i32_be(payload, 0),
        secret_key=read_i32_be(payload, 4),
      )
    }
    b'S' => {
      let (name, p1) = read_cstr(payload, 0)
      let (value, _) = read_cstr(payload, p1)
      BackendMessage::ParameterStatus(name~, value~)
    }
    b'Z' => {
      if payload.length() < 1 {
        raise @codec.DataError::ProtocolError("truncated ReadyForQuery")
      }
      BackendMessage::ReadyForQuery(status=payload[0])
    }
    b'1' => BackendMessage::ParseComplete
    b'2' => BackendMessage::BindComplete
    b'3' => BackendMessage::CloseComplete
    b'I' => BackendMessage::EmptyQueryResponse
    b'n' => BackendMessage::NoData
    b's' => BackendMessage::PortalSuspended
    b't' => {
      if payload.length() < 2 {
        raise @codec.DataError::ProtocolError("truncated ParameterDescription")
      }
      let cnt = read_i16_be(payload, 0)
      let oids : Array[Int32] = []
      let mut pos = 2
      for _ in 0.. payload.length() {
          raise @codec.DataError::ProtocolError(
            "truncated OID in ParameterDescription",
          )
        }
        oids.push(read_i32_be(payload, pos))
        pos += 4
      }
      BackendMessage::ParameterDescription(oids)
    }
    b'T' => parse_row_description(payload)
    b'D' => parse_data_row(payload)
    b'C' => {
      let (cmd_tag, _) = read_cstr(payload, 0)
      BackendMessage::CommandComplete(cmd_tag)
    }
    b'E' => BackendMessage::ErrorResponse(parse_error_fields(payload))
    b'N' => BackendMessage::NoticeResponse(parse_error_fields(payload))
    _ => BackendMessage::Unknown(tag~, payload=payload.to_owned())
  }
  Some((msg, total_len))
}

///|
/// Stateful streaming PG backend message decoder using a cursor buffer to avoid O(N^2) copies.
pub struct PgDecoder {
  priv buf : Array[Byte]
  priv mut head : Int32
}

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

///|
pub fn PgDecoder::feed(self : PgDecoder, chunk : BytesView) -> Unit {
  if chunk.length() == 0 {
    return
  }
  for b in chunk {
    self.buf.push(b)
  }
}

///|
pub fn PgDecoder::next_message(
  self : PgDecoder,
) -> BackendMessage? raise @codec.DataError {
  let avail = self.buf.length() - self.head
  if avail < 5 {
    return None
  }
  let b0 = self.buf[self.head + 1].to_int()
  let b1 = self.buf[self.head + 2].to_int()
  let b2 = self.buf[self.head + 3].to_int()
  let b3 = self.buf[self.head + 4].to_int()
  let msg_len = (b0 << 24) | (b1 << 16) | (b2 << 8) | b3
  if msg_len < 4 || msg_len > MAX_PG_MESSAGE_LEN {
    raise @codec.DataError::ProtocolError(
      "invalid PG message length: \{msg_len}",
    )
  }
  if avail - 1 < msg_len {
    return None
  }
  let total_len = 1 + msg_len
  let frame = Bytes::from_array(self.buf[self.head:self.head + total_len])
  match decode_backend_message(frame[:]) {
    None => None
    Some((msg, consumed)) => {
      self.head += consumed
      if self.head >= self.buf.length() {
        self.buf.clear()
        self.head = 0
      } else if self.head >= 4096 && self.head * 2 >= self.buf.length() {
        let rem_len = self.buf.length() - self.head
        for i in 0.. rem_len {
          ignore(self.buf.pop())
        }
        self.head = 0
      }
      Some(msg)
    }
  }
}