///|
pub const MSG_HANDSHAKE_INITIATION : Byte = b'\x01'

///|
pub const MSG_HANDSHAKE_RESPONSE : Byte = b'\x02'

///|
pub const MSG_COOKIE_REPLY : Byte = b'\x03'

///|
pub const MSG_TRANSPORT_DATA : Byte = b'\x04'

///|
pub const HANDSHAKE_INITIATION_LEN : Int32 = 148

///|
pub const HANDSHAKE_RESPONSE_LEN : Int32 = 92

///|
pub const COOKIE_REPLY_LEN : Int32 = 64

///|
pub const TRANSPORT_HEADER_LEN : Int32 = 16

///|
pub const AEAD_TAG_LEN : Int32 = 16

///|
#derive(Debug, Eq)
pub(all) suberror PacketError {
  EmptyPacket
  UnknownMessageType(Byte)
  InvalidPacketLength(msg_type~ : Byte, expected~ : Int32, actual~ : Int32)
  NonZeroReservedBytes
  InvalidFieldLength(field~ : String, expected~ : Int32, actual~ : Int32)
  InvalidInnerIpPacket(String)
  InvalidIpAddress(String)
}

///|
/// Type 1: WireGuard Handshake Initiation message (148 bytes, §5.4.2).
#derive(Debug, Eq)
pub(all) struct HandshakeInitiation {
  sender_index : UInt32
  unencrypted_ephemeral : Bytes
  encrypted_static : Bytes
  encrypted_timestamp : Bytes
  mac1 : Bytes
  mac2 : Bytes
}

///|
/// Type 2: WireGuard Handshake Response message (92 bytes, §5.4.3).
#derive(Debug, Eq)
pub(all) struct HandshakeResponse {
  sender_index : UInt32
  receiver_index : UInt32
  unencrypted_ephemeral : Bytes
  encrypted_nothing : Bytes
  mac1 : Bytes
  mac2 : Bytes
}

///|
/// Type 3: WireGuard Cookie Reply message (64 bytes, §5.4.7).
#derive(Debug, Eq)
pub(all) struct CookieReply {
  receiver_index : UInt32
  nonce : Bytes
  encrypted_cookie : Bytes
}

///|
/// Type 4: WireGuard Transport Data message (>= 32 bytes, §5.4.6).
#derive(Debug, Eq)
pub(all) struct TransportData {
  receiver_index : UInt32
  counter : UInt64
  encrypted_packet : Bytes
}

///|
/// Parsed WireGuard outer UDP frame.
#derive(Debug, Eq)
pub(all) enum WirePacket {
  Initiation(HandshakeInitiation)
  Response(HandshakeResponse)
  Cookie(CookieReply)
  Transport(TransportData)
}

///|
fn check_field_len(
  field : String,
  b : Bytes,
  expected : Int32,
) -> Unit raise PacketError {
  if b.length() != expected {
    raise PacketError::InvalidFieldLength(field~, expected~, actual=b.length())
  }
}

///|
/// Encode `HandshakeInitiation` into its canonical 148-byte wire format.
pub fn HandshakeInitiation::encode(
  self : HandshakeInitiation,
) -> Bytes raise PacketError {
  check_field_len("unencrypted_ephemeral", self.unencrypted_ephemeral, 32)
  check_field_len("encrypted_static", self.encrypted_static, 48)
  check_field_len("encrypted_timestamp", self.encrypted_timestamp, 28)
  check_field_len("mac1", self.mac1, 16)
  check_field_len("mac2", self.mac2, 16)
  let out = FixedArray::make(HANDSHAKE_INITIATION_LEN, b'\x00')
  out[0] = MSG_HANDSHAKE_INITIATION
  @crypto.write_u32_le(out, 4, self.sender_index)
  for i in 0..<32 {
    out[8 + i] = self.unencrypted_ephemeral[i]
  }
  for i in 0..<48 {
    out[40 + i] = self.encrypted_static[i]
  }
  for i in 0..<28 {
    out[88 + i] = self.encrypted_timestamp[i]
  }
  for i in 0..<16 {
    out[116 + i] = self.mac1[i]
  }
  for i in 0..<16 {
    out[132 + i] = self.mac2[i]
  }
  Bytes::from_array(out)
}

///|
/// Encode the 116-byte prefix `[0..116)` covered by `mac1` for `HandshakeInitiation`.
pub fn HandshakeInitiation::encode_prefix_for_mac1(
  sender_index : UInt32,
  unencrypted_ephemeral : BytesView,
  encrypted_static : BytesView,
  encrypted_timestamp : BytesView,
) -> Bytes {
  let out = FixedArray::make(116, b'\x00')
  out[0] = MSG_HANDSHAKE_INITIATION
  @crypto.write_u32_le(out, 4, sender_index)
  for i in 0..<32 {
    out[8 + i] = unencrypted_ephemeral[i]
  }
  for i in 0..<48 {
    out[40 + i] = encrypted_static[i]
  }
  for i in 0..<28 {
    out[88 + i] = encrypted_timestamp[i]
  }
  Bytes::from_array(out)
}

///|
/// Encode `HandshakeResponse` into its canonical 92-byte wire format.
pub fn HandshakeResponse::encode(
  self : HandshakeResponse,
) -> Bytes raise PacketError {
  check_field_len("unencrypted_ephemeral", self.unencrypted_ephemeral, 32)
  check_field_len("encrypted_nothing", self.encrypted_nothing, 16)
  check_field_len("mac1", self.mac1, 16)
  check_field_len("mac2", self.mac2, 16)
  let out = FixedArray::make(HANDSHAKE_RESPONSE_LEN, b'\x00')
  out[0] = MSG_HANDSHAKE_RESPONSE
  @crypto.write_u32_le(out, 4, self.sender_index)
  @crypto.write_u32_le(out, 8, self.receiver_index)
  for i in 0..<32 {
    out[12 + i] = self.unencrypted_ephemeral[i]
  }
  for i in 0..<16 {
    out[44 + i] = self.encrypted_nothing[i]
  }
  for i in 0..<16 {
    out[60 + i] = self.mac1[i]
  }
  for i in 0..<16 {
    out[76 + i] = self.mac2[i]
  }
  Bytes::from_array(out)
}

///|
/// Encode the 60-byte prefix `[0..60)` covered by `mac1` for `HandshakeResponse`.
pub fn HandshakeResponse::encode_prefix_for_mac1(
  sender_index : UInt32,
  receiver_index : UInt32,
  unencrypted_ephemeral : BytesView,
  encrypted_nothing : BytesView,
) -> Bytes {
  let out = FixedArray::make(60, b'\x00')
  out[0] = MSG_HANDSHAKE_RESPONSE
  @crypto.write_u32_le(out, 4, sender_index)
  @crypto.write_u32_le(out, 8, receiver_index)
  for i in 0..<32 {
    out[12 + i] = unencrypted_ephemeral[i]
  }
  for i in 0..<16 {
    out[44 + i] = encrypted_nothing[i]
  }
  Bytes::from_array(out)
}

///|
/// Encode `CookieReply` into its canonical 64-byte wire format.
pub fn CookieReply::encode(self : CookieReply) -> Bytes raise PacketError {
  check_field_len("nonce", self.nonce, 24)
  check_field_len("encrypted_cookie", self.encrypted_cookie, 32)
  let out = FixedArray::make(COOKIE_REPLY_LEN, b'\x00')
  out[0] = MSG_COOKIE_REPLY
  @crypto.write_u32_le(out, 4, self.receiver_index)
  for i in 0..<24 {
    out[8 + i] = self.nonce[i]
  }
  for i in 0..<32 {
    out[32 + i] = self.encrypted_cookie[i]
  }
  Bytes::from_array(out)
}

///|
/// Encode `TransportData` into wire bytes (`16-byte header || encrypted_packet`).
pub fn TransportData::encode(self : TransportData) -> Bytes raise PacketError {
  if self.encrypted_packet.length() < AEAD_TAG_LEN {
    raise PacketError::InvalidFieldLength(
      field="encrypted_packet",
      expected=AEAD_TAG_LEN,
      actual=self.encrypted_packet.length(),
    )
  }
  let total = TRANSPORT_HEADER_LEN + self.encrypted_packet.length()
  let out = FixedArray::make(total, b'\x00')
  out[0] = MSG_TRANSPORT_DATA
  @crypto.write_u32_le(out, 4, self.receiver_index)
  @crypto.write_u64_le(out, 8, self.counter)
  for i in 0.. Bytes raise PacketError {
  match self {
    Initiation(m) => m.encode()
    Response(m) => m.encode()
    Cookie(m) => m.encode()
    Transport(m) => m.encode()
  }
}

///|
/// Parse raw UDP datagram bytes into a typed `WirePacket`.
/// When `strict_reserved` is true, non-zero reserved bytes `[1..4)` raise `NonZeroReservedBytes`.
pub fn parse_wire_packet(
  raw : BytesView,
  strict_reserved~ : Bool = false,
) -> WirePacket raise PacketError {
  if raw.length() == 0 {
    raise PacketError::EmptyPacket
  }
  let msg_type = raw[0]
  if raw.length() >= 4 && strict_reserved {
    if raw[1] != b'\x00' || raw[2] != b'\x00' || raw[3] != b'\x00' {
      raise PacketError::NonZeroReservedBytes
    }
  }
  match msg_type {
    b'\x01' => {
      if raw.length() != HANDSHAKE_INITIATION_LEN {
        raise PacketError::InvalidPacketLength(
          msg_type~,
          expected=HANDSHAKE_INITIATION_LEN,
          actual=raw.length(),
        )
      }
      Initiation({
        sender_index: @crypto.read_u32_le(raw, 4),
        unencrypted_ephemeral: raw[8:40].to_owned(),
        encrypted_static: raw[40:88].to_owned(),
        encrypted_timestamp: raw[88:116].to_owned(),
        mac1: raw[116:132].to_owned(),
        mac2: raw[132:148].to_owned(),
      })
    }
    b'\x02' => {
      if raw.length() != HANDSHAKE_RESPONSE_LEN {
        raise PacketError::InvalidPacketLength(
          msg_type~,
          expected=HANDSHAKE_RESPONSE_LEN,
          actual=raw.length(),
        )
      }
      Response({
        sender_index: @crypto.read_u32_le(raw, 4),
        receiver_index: @crypto.read_u32_le(raw, 8),
        unencrypted_ephemeral: raw[12:44].to_owned(),
        encrypted_nothing: raw[44:60].to_owned(),
        mac1: raw[60:76].to_owned(),
        mac2: raw[76:92].to_owned(),
      })
    }
    b'\x03' => {
      if raw.length() != COOKIE_REPLY_LEN {
        raise PacketError::InvalidPacketLength(
          msg_type~,
          expected=COOKIE_REPLY_LEN,
          actual=raw.length(),
        )
      }
      Cookie({
        receiver_index: @crypto.read_u32_le(raw, 4),
        nonce: raw[8:32].to_owned(),
        encrypted_cookie: raw[32:64].to_owned(),
      })
    }
    b'\x04' => {
      if raw.length() < TRANSPORT_HEADER_LEN + AEAD_TAG_LEN {
        raise PacketError::InvalidPacketLength(
          msg_type~,
          expected=TRANSPORT_HEADER_LEN + AEAD_TAG_LEN,
          actual=raw.length(),
        )
      }
      Transport({
        receiver_index: @crypto.read_u32_le(raw, 4),
        counter: @crypto.read_u64_le(raw, 8),
        encrypted_packet: raw[16:].to_owned(),
      })
    }
    _ => raise PacketError::UnknownMessageType(msg_type)
  }
}

///|
/// Pad an inner IP packet with trailing `0x00` bytes to a multiple of 16 bytes (WireGuard §5.4.6).
pub fn pad_inner_packet(plaintext : BytesView) -> Bytes {
  let len = plaintext.length()
  let rem = len % 16
  if rem == 0 {
    plaintext.to_owned()
  } else {
    let padded_len = len + (16 - rem)
    let out = FixedArray::make(padded_len, b'\x00')
    for i in 0..