///|
#derive(Debug, Eq)
pub(all) suberror RoutingError {
  MissingPrefixLength(String)
  InvalidPrefixLength(Int32)
  Address(@packet.PacketError)
}

///|
/// Canonical masked IPv4 (`0..=32`) or IPv6 (`0..=128`) CIDR network prefix.
#derive(Debug, Eq)
pub(all) struct Cidr {
  network : @packet.IpAddr
  prefix_len : Int32
}

///|
pub fn Cidr::to_text(self : Cidr) -> String {
  "\{self.network.to_text()}/\{self.prefix_len}"
}

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

///|
fn mask_ipv4(raw : UInt32, prefix_len : Int32) -> UInt32 {
  if prefix_len <= 0 {
    0U
  } else if prefix_len >= 32 {
    raw
  } else {
    let shift = 32 - prefix_len
    raw >> shift << shift
  }
}

///|
fn mask_ipv6(raw16 : BytesView, prefix_len : Int32) -> Bytes {
  let out = FixedArray::make(16, b'\x00')
  let full_bytes = prefix_len / 8
  let rem_bits = prefix_len % 8
  for i in 0.. 0 && full_bytes < 16 {
    let mask = (0xff << (8 - rem_bits)) & 0xff
    out[full_bytes] = (raw16[full_bytes].to_int() & mask).to_byte()
  }
  Bytes::from_array(out)
}

///|
/// Parse `"/"` into `(canonical_cidr, had_nonzero_host_bits)`.
pub fn parse_cidr_detailed(
  text : StringView,
) -> (Cidr, Bool) raise RoutingError {
  let mut slash = -1
  for i in 0..= text.length() {
    raise RoutingError::MissingPrefixLength(text.to_owned())
  }
  let ip_part = text[:slash]
  let len_part = text[slash + 1:]
  let raw_ip = @packet.parse_ip_addr(ip_part) catch {
    err => raise RoutingError::Address(err)
  }
  let mut plen = 0
  for i in 0.. '9' {
      raise RoutingError::InvalidPrefixLength(-1)
    }
    plen = plen * 10 + (ch.to_int() - '0'.to_int())
  }
  match raw_ip {
    V4(u) => {
      if plen < 0 || plen > 32 {
        raise RoutingError::InvalidPrefixLength(plen)
      }
      let masked = mask_ipv4(u, plen)
      ({ network: V4(masked), prefix_len: plen, }, masked != u)
    }
    V6(b) => {
      if plen < 0 || plen > 128 {
        raise RoutingError::InvalidPrefixLength(plen)
      }
      let masked = mask_ipv6(b, plen)
      ({ network: V6(masked), prefix_len: plen, }, masked != b)
    }
  }
}

///|
/// Parse `"/"` and canonicalize host bits to zero.
pub fn parse_cidr(text : StringView) -> Cidr raise RoutingError {
  let (cidr, _) = parse_cidr_detailed(text)
  cidr
}

///|
/// Return `true` if `super_cidr` covers `sub_cidr` (`super_cidr.prefix_len <= sub_cidr.prefix_len` and prefixes match).
pub fn Cidr::contains_cidr(self : Cidr, sub : Cidr) -> Bool {
  match (self.network, sub.network) {
    (V4(a), V4(b)) =>
      self.prefix_len <= sub.prefix_len && mask_ipv4(b, self.prefix_len) == a
    (V6(a), V6(b)) =>
      self.prefix_len <= sub.prefix_len && mask_ipv6(b, self.prefix_len) == a
    _ => false
  }
}

///|
priv struct TrieNode[V] {
  mut zero : TrieNode[V]?
  mut one : TrieNode[V]?
  mut value : V?
}

///|
fn[V] TrieNode::new() -> TrieNode[V] {
  { zero: None, one: None, value: None, }
}

///|
/// WireGuard Cryptokey Routing longest-prefix-match binary radix trie (§4) supporting both IPv4 and IPv6.
pub struct RoutingTable[V] {
  priv v4_root : TrieNode[V]
  priv v6_root : TrieNode[V]
}

///|
pub fn[V] RoutingTable::new() -> RoutingTable[V] {
  { v4_root: TrieNode::new(), v6_root: TrieNode::new(), }
}

///|
fn v4_bit(addr : UInt32, depth : Int32) -> Int32 {
  ((addr >> (31 - depth)) & 1U).reinterpret_as_int()
}

///|
fn v6_bit(addr16 : BytesView, depth : Int32) -> Int32 {
  let byte_idx = depth >> 3
  let bit_idx = 7 - (depth & 7)
  (addr16[byte_idx].to_int() >> bit_idx) & 1
}

///|
/// Associate `cidr` with `peer` in the Cryptokey Routing table.
pub fn[V] RoutingTable::insert(
  self : RoutingTable[V],
  cidr : Cidr,
  peer : V,
) -> Unit {
  match cidr.network {
    V4(u) => {
      let mut curr = self.v4_root
      for d in 0.. curr = next
            None => {
              let node = TrieNode::new()
              curr.zero = Some(node)
              curr = node
            }
          }
        } else {
          match curr.one {
            Some(next) => curr = next
            None => {
              let node = TrieNode::new()
              curr.one = Some(node)
              curr = node
            }
          }
        }
      }
      curr.value = Some(peer)
    }
    V6(b) => {
      let mut curr = self.v6_root
      for d in 0.. curr = next
            None => {
              let node = TrieNode::new()
              curr.zero = Some(node)
              curr = node
            }
          }
        } else {
          match curr.one {
            Some(next) => curr = next
            None => {
              let node = TrieNode::new()
              curr.one = Some(node)
              curr = node
            }
          }
        }
      }
      curr.value = Some(peer)
    }
  }
}

///|
/// Longest-prefix-match lookup for destination or source `addr`.
pub fn[V] RoutingTable::lookup(
  self : RoutingTable[V],
  addr : @packet.IpAddr,
) -> V? {
  match addr {
    V4(u) => {
      let mut best = self.v4_root.value
      let mut curr : TrieNode[V]? = Some(self.v4_root)
      let mut d = 0
      while d < 32 {
        match curr {
          None => break
          Some(node) => {
            if node.value is Some(v) {
              best = Some(v)
            }
            curr = if v4_bit(u, d) == 0 { node.zero } else { node.one }
            if d == 31 {
              if curr is Some(leaf) && leaf.value is Some(v) {
                best = Some(v)
              }
            }
            d = d + 1
          }
        }
      }
      best
    }
    V6(b) => {
      let mut best = self.v6_root.value
      let mut curr : TrieNode[V]? = Some(self.v6_root)
      let mut d = 0
      while d < 128 {
        match curr {
          None => break
          Some(node) => {
            if node.value is Some(v) {
              best = Some(v)
            }
            curr = if v6_bit(b, d) == 0 { node.zero } else { node.one }
            if d == 127 {
              if curr is Some(leaf) && leaf.value is Some(v) {
                best = Some(v)
              }
            }
            d = d + 1
          }
        }
      }
      best
    }
  }
}

///|
/// Cryptokey Routing reverse-path source IP check (§4): returns `true` iff `src_addr` longest-prefix-matches `expected_peer`.
pub fn[V : Eq] RoutingTable::verify_source(
  self : RoutingTable[V],
  src_addr : @packet.IpAddr,
  expected_peer : V,
) -> Bool {
  match self.lookup(src_addr) {
    Some(owner) => owner == expected_peer
    None => false
  }
}

///|
/// Static routing overlap / shadowing findings across peer `AllowedIPs` declarations.
#derive(Debug, Eq)
pub(all) enum RouteOverlapKind {
  ExactDuplicateConflict
  RedundantSelfSubset
  CrossPeerSubnetCarve
}

///|
#derive(Debug, Eq)
pub(all) struct RouteOverlapFinding {
  kind : RouteOverlapKind
  wider_peer : String
  wider_cidr : Cidr
  narrower_peer : String
  narrower_cidr : Cidr
}

///|
/// Analyze a list of `(peer_id, allowed_cidrs)` pairs for exact route collisions, self-redundant subsets,
/// and cross-peer subnet carving.
pub fn analyze_overlaps(
  peer_routes : Array[(String, Array[Cidr])],
) -> Array[RouteOverlapFinding] {
  let flat : Array[(String, Cidr)] = []
  for entry in peer_routes {
    let (peer_id, cidrs) = entry
    for c in cidrs {
      flat.push((peer_id, c))
    }
  }
  let findings : Array[RouteOverlapFinding] = []
  let n = flat.length()
  for i in 0..