///|
/// Canonical IPv4 or IPv6 network address.
#derive(Debug, Eq)
pub(all) enum IpAddr {
  V4(UInt32)
  V6(Bytes)
}

///|
/// Parsed metadata and padding-trimmed slice of an inner encapsulated IPv4 or IPv6 packet.
#derive(Debug, Eq)
pub(all) struct InnerIpInfo {
  version : Int32
  src : IpAddr
  dst : IpAddr
  next_proto : Byte
  total_len : Int32
  trimmed_packet : Bytes
}

///|
pub fn read_u16_be(data : BytesView, offset : Int32) -> Int32 {
  (data[offset].to_int() << 8) | data[offset + 1].to_int()
}

///|
pub fn write_u16_be(
  out : FixedArray[Byte],
  offset : Int32,
  val : Int32,
) -> Unit {
  out[offset] = ((val >> 8) & 0xff).to_byte()
  out[offset + 1] = (val & 0xff).to_byte()
}

///|
/// Construct `IpAddr::V4` from four octets `a.b.c.d`.
pub fn ipv4(a : Byte, b : Byte, c : Byte, d : Byte) -> IpAddr {
  V4(
    (a.to_uint() << 24) | (b.to_uint() << 16) | (c.to_uint() << 8) | d.to_uint(),
  )
}

///|
/// Construct `IpAddr::V6` from 16 raw big-endian bytes.
pub fn ipv6_from_bytes(raw16 : BytesView) -> IpAddr raise PacketError {
  if raw16.length() != 16 {
    raise PacketError::InvalidIpAddress("IPv6 address requires 16 bytes")
  }
  V6(raw16.to_owned())
}

///|
/// Format `IpAddr` into human-readable dotted-quad or colon-hex text.
pub fn IpAddr::to_text(self : IpAddr) -> String {
  match self {
    V4(u) => {
      let a = (u >> 24) & 0xffU
      let b = (u >> 16) & 0xffU
      let c = (u >> 8) & 0xffU
      let d = u & 0xffU
      "\{a}.\{b}.\{c}.\{d}"
    }
    V6(bytes) => {
      let sb = StringBuilder()
      for i in 0..<8 {
        if i > 0 {
          sb.write_char(':')
        }
        let group = read_u16_be(bytes, i * 2)
        let hex_digits = "0123456789abcdef"
        let mut started = false
        for shift_idx in 0..<4 {
          let shift = (3 - shift_idx) * 4
          let nib = (group >> shift) & 0x0f
          if nib != 0 || started || shift_idx == 3 {
            sb.write_char(hex_digits[nib].to_int().unsafe_to_char())
            started = true
          }
        }
      }
      sb.to_string()
    }
  }
}

///|
pub impl Show for IpAddr with fn output(self, logger) {
  logger.write_string(self.to_text())
}

///|
fn parse_decimal_octet(s : StringView) -> UInt32 raise PacketError {
  if s.length() == 0 || s.length() > 3 {
    raise PacketError::InvalidIpAddress("invalid IPv4 octet")
  }
  if s.length() > 1 && s[0] == '0' {
    raise PacketError::InvalidIpAddress("leading zero in IPv4 octet")
  }
  let mut acc = 0
  for i in 0.. '9' {
      raise PacketError::InvalidIpAddress("non-digit in IPv4 octet")
    }
    acc = acc * 10 + (ch.to_int() - '0'.to_int())
  }
  if acc > 255 {
    raise PacketError::InvalidIpAddress("IPv4 octet > 255")
  }
  acc.reinterpret_as_uint()
}

///|
/// Parse an IPv4 (`a.b.c.d`) or IPv6 (`::` compressed or full 8-group hex) address string.
pub fn parse_ip_addr(text : StringView) -> IpAddr raise PacketError {
  let mut has_colon = false
  for i in 0.. Int32 raise PacketError {
  if s.length() == 0 || s.length() > 4 {
    raise PacketError::InvalidIpAddress("invalid IPv6 group length")
  }
  let mut v = 0
  for i in 0..= '0' && ch <= '9' {
      ch.to_int() - '0'.to_int()
    } else if ch >= 'a' && ch <= 'f' {
      ch.to_int() - 'a'.to_int() + 10
    } else if ch >= 'A' && ch <= 'F' {
      ch.to_int() - 'A'.to_int() + 10
    } else {
      raise PacketError::InvalidIpAddress("invalid hex digit in IPv6 address")
    }
    v = (v << 4) | nib
  }
  v
}

///|
fn parse_ipv6_groups(part : StringView) -> Array[Int32] raise PacketError {
  if part.length() == 0 {
    []
  } else {
    let groups : Array[Int32] = []
    let mut start = 0
    for i in 0..<=part.length() {
      if i == part.length() || part[i] == ':' {
        let seg = part[start:i]
        groups.push(parse_hex_group(seg))
        start = i + 1
      }
    }
    groups
  }
}

///|
fn parse_ipv6_addr(text : StringView) -> IpAddr raise PacketError {
  let len = text.length()
  if len < 2 {
    raise PacketError::InvalidIpAddress("IPv6 address too short")
  }
  let mut dbl_idx = -1
  let mut i = 0
  while i + 1 < len {
    if text[i] == ':' && text[i + 1] == ':' {
      if dbl_idx != -1 {
        raise PacketError::InvalidIpAddress("multiple '::' in IPv6 address")
      }
      dbl_idx = i
      i = i + 2
    } else {
      i = i + 1
    }
  }
  let full_groups = FixedArray::make(8, 0)
  if dbl_idx == -1 {
    let gs = parse_ipv6_groups(text)
    if gs.length() != 8 {
      raise PacketError::InvalidIpAddress("IPv6 address requires 8 groups")
    }
    for j in 0..<8 {
      full_groups[j] = gs[j]
    }
  } else {
    let left_str = text[:dbl_idx]
    let right_str = text[dbl_idx + 2:]
    let left = parse_ipv6_groups(left_str)
    let right = parse_ipv6_groups(right_str)
    if left.length() + right.length() >= 8 {
      raise PacketError::InvalidIpAddress("too many groups in compressed IPv6")
    }
    for j in 0.. InnerIpInfo raise PacketError {
  if decrypted.length() < 20 {
    raise PacketError::InvalidInnerIpPacket(
      "inner packet shorter than 20 bytes",
    )
  }
  let ver = (decrypted[0].to_int() >> 4) & 0x0f
  if ver == 4 {
    let ihl = (decrypted[0].to_int() & 0x0f) * 4
    if ihl < 20 || ihl > decrypted.length() {
      raise PacketError::InvalidInnerIpPacket("invalid IPv4 IHL")
    }
    let total_len = read_u16_be(decrypted, 2)
    if total_len < ihl || total_len > decrypted.length() {
      raise PacketError::InvalidInnerIpPacket(
        "IPv4 total_length out of decrypted buffer bounds",
      )
    }
    let src = ipv4(decrypted[12], decrypted[13], decrypted[14], decrypted[15])
    let dst = ipv4(decrypted[16], decrypted[17], decrypted[18], decrypted[19])
    {
      version: 4,
      src,
      dst,
      next_proto: decrypted[9],
      total_len,
      trimmed_packet: decrypted[:total_len].to_owned(),
    }
  } else if ver == 6 {
    if decrypted.length() < 40 {
      raise PacketError::InvalidInnerIpPacket(
        "IPv6 packet shorter than 40-byte fixed header",
      )
    }
    let payload_len = read_u16_be(decrypted, 4)
    let total_len = 40 + payload_len
    if total_len > decrypted.length() {
      raise PacketError::InvalidInnerIpPacket(
        "IPv6 payload_length exceeds decrypted buffer",
      )
    }
    let src = V6(decrypted[8:24].to_owned())
    let dst = V6(decrypted[24:40].to_owned())
    {
      version: 6,
      src,
      dst,
      next_proto: decrypted[6],
      total_len,
      trimmed_packet: decrypted[:total_len].to_owned(),
    }
  } else {
    raise PacketError::InvalidInnerIpPacket("unsupported IP version \{ver}")
  }
}

///|
/// RFC 1071 16-bit one's complement Internet checksum.
pub fn internet_checksum(data : BytesView) -> Int32 {
  let mut sum = 0
  let len = data.length()
  let mut i = 0
  while i + 1 < len {
    sum = sum + read_u16_be(data, i)
    i = i + 2
  }
  if i < len {
    sum = sum + (data[i].to_int() << 8)
  }
  while sum >> 16 != 0 {
    sum = (sum & 0xffff) + (sum >> 16)
  }
  sum.lnot() & 0xffff
}

///|
/// Build a standards-compliant IPv4 ICMP Echo Request (`icmp_type = 8`) or Reply (`icmp_type = 0`) packet
/// with valid IPv4 header and ICMP checksums for userspace tunnel testing.
pub fn build_ipv4_icmp_echo(
  src_v4 : UInt32,
  dst_v4 : UInt32,
  identifier : Int32,
  sequence : Int32,
  payload : BytesView,
  is_reply~ : Bool = false,
) -> Bytes {
  let icmp_len = 8 + payload.length()
  let total_len = 20 + icmp_len
  let pkt = FixedArray::make(total_len, b'\x00')
  pkt[0] = b'\x45'
  write_u16_be(pkt, 2, total_len)
  write_u16_be(pkt, 4, sequence & 0xffff)
  pkt[6] = b'\x40' // Don't Fragment
  pkt[8] = b'\x40' // TTL = 64
  pkt[9] = b'\x01' // Protocol = ICMPv4
  pkt[12] = ((src_v4 >> 24) & 0xffU).to_byte()
  pkt[13] = ((src_v4 >> 16) & 0xffU).to_byte()
  pkt[14] = ((src_v4 >> 8) & 0xffU).to_byte()
  pkt[15] = (src_v4 & 0xffU).to_byte()
  pkt[16] = ((dst_v4 >> 24) & 0xffU).to_byte()
  pkt[17] = ((dst_v4 >> 16) & 0xffU).to_byte()
  pkt[18] = ((dst_v4 >> 8) & 0xffU).to_byte()
  pkt[19] = (dst_v4 & 0xffU).to_byte()

  let ip_csum = internet_checksum(Bytes::from_array(pkt)[:20])
  write_u16_be(pkt, 10, ip_csum)

  pkt[20] = if is_reply { b'\x00' } else { b'\x08' }
  pkt[21] = b'\x00'
  write_u16_be(pkt, 24, identifier & 0xffff)
  write_u16_be(pkt, 26, sequence & 0xffff)
  for i in 0.. String {
  if decrypted.length() == 0 {
    "Keepalive (0 bytes)"
  } else {
    let info_res : Result[InnerIpInfo, PacketError] = Ok(
      inspect_and_trim_inner_ip(decrypted),
    ) catch {
      err => Err(err)
    }
    match info_res {
      Err(_) => "MalformedInnerPacket(\{decrypted.length()} bytes)"
      Ok(info) => {
        let p = info.trimmed_packet
        let proto_desc = if info.version == 4 &&
          info.next_proto == b'\x01' &&
          p.length() >= 28 {
          let ihl = (p[0].to_int() & 0x0f) * 4
          if ihl + 8 <= p.length() {
            let icmp_type = p[ihl].to_int()
            let seq = read_u16_be(p, ihl + 6)
            if icmp_type == 8 {
              "ICMPv4 Echo Request seq=\{seq}"
            } else if icmp_type == 0 {
              "ICMPv4 Echo Reply seq=\{seq}"
            } else {
              "ICMPv4 type=\{icmp_type}"
            }
          } else {
            "ICMPv4"
          }
        } else if info.next_proto == b'\x06' {
          let hdr_len = if info.version == 4 {
            (p[0].to_int() & 0x0f) * 4
          } else {
            40
          }
          if hdr_len + 4 <= p.length() {
            let sport = read_u16_be(p, hdr_len)
            let dport = read_u16_be(p, hdr_len + 2)
            "TCP \{sport}->\{dport}"
          } else {
            "TCP"
          }
        } else if info.next_proto == b'\x11' {
          let hdr_len = if info.version == 4 {
            (p[0].to_int() & 0x0f) * 4
          } else {
            40
          }
          if hdr_len + 4 <= p.length() {
            let sport = read_u16_be(p, hdr_len)
            let dport = read_u16_be(p, hdr_len + 2)
            "UDP \{sport}->\{dport}"
          } else {
            "UDP"
          }
        } else if info.next_proto == b'\x3a' {
          "ICMPv6"
        } else {
          "proto=\{info.next_proto.to_int()}"
        }
        "IPv\{info.version} \{info.src} -> \{info.dst} (\{proto_desc}, \{info.total_len}B)"
      }
    }
  }
}