///|
/// Multi-peer Sans-IO WireGuard interface engine uniting per-peer Noise tunnels,
/// `CookieValidator` DoS mitigation, and §4 Cryptokey Routing (outbound LPM + inbound source anti-spoofing).
pub struct Device {
  local_static_private : Bytes
  local_static_public : Bytes
  priv mut seed_chain : Bytes
  cookies : CookieValidator
  routing : @routing.RoutingTable[Int32]
  peers : Array[PeerTunnel]
}

///|
/// Create a multi-peer Sans-IO `Device` from a 32-byte `local_static_private` key and 32-byte `entropy_seed`.
pub fn Device::new(
  local_static_private : BytesView,
  entropy_seed : BytesView,
  now_ms : UInt64,
) -> Device raise ProtocolError {
  ensure_key32("local_static_private", local_static_private)
  ensure_key32("entropy_seed", entropy_seed)
  let local_static_public = @crypto.x25519_public_key(local_static_private) catch {
    err => raise ProtocolError::Crypto(err)
  }
  let (next_seed, cookie_seed) = @crypto.kdf2(entropy_seed, b"device-cookie")
  let cookies = CookieValidator::new(local_static_public, cookie_seed, now_ms)
  {
    local_static_private: local_static_private.to_owned(),
    local_static_public,
    seed_chain: next_seed,
    cookies,
    routing: @routing.RoutingTable::new(),
    peers: [],
  }
}

///|
/// Register a peer and its `AllowedIPs` prefixes on the device, returning the assigned `peer_id` (`0..N-1`).
pub fn Device::add_peer(
  self : Device,
  remote_static_public : BytesView,
  allowed_ips : Array[@routing.Cidr],
  preshared_key? : BytesView,
  persistent_keepalive_ms? : UInt64,
) -> Int32 raise ProtocolError {
  let peer_id = self.peers.length()
  let (next_seed, peer_seed) = @crypto.kdf2(self.seed_chain, b"device-peer")
  self.seed_chain = next_seed
  // Partition sender_index space by peer_id so indices never collide across peers on the same device
  let base_index = ((peer_id + 1).reinterpret_as_uint() << 20) | 1U
  let peer = match (preshared_key, persistent_keepalive_ms) {
    (Some(psk), Some(ka)) =>
      PeerTunnel::new(
        self.local_static_private,
        remote_static_public,
        peer_seed,
        initial_index=base_index,
        preshared_key=psk,
        persistent_keepalive_ms=ka,
      )
    (Some(psk), None) =>
      PeerTunnel::new(
        self.local_static_private,
        remote_static_public,
        peer_seed,
        initial_index=base_index,
        preshared_key=psk,
      )
    (None, Some(ka)) =>
      PeerTunnel::new(
        self.local_static_private,
        remote_static_public,
        peer_seed,
        initial_index=base_index,
        persistent_keepalive_ms=ka,
      )
    (None, None) =>
      PeerTunnel::new(
        self.local_static_private,
        remote_static_public,
        peer_seed,
        initial_index=base_index,
      )
  }
  self.peers.push(peer)
  for cidr in allowed_ips {
    self.routing.insert(cidr, peer_id)
  }
  peer_id
}

///|
/// Route an outbound inner IPv4/IPv6 packet via Cryptokey Routing LPM and encapsulate it for the matched peer.
/// Returns `(peer_id, outbound_udp_datagrams)`.
pub fn Device::route_and_encapsulate(
  self : Device,
  inner_ip : BytesView,
  now_ms : UInt64,
) -> (Int32, Array[Bytes]) raise ProtocolError {
  let info = @packet.inspect_and_trim_inner_ip(inner_ip) catch {
    err => raise ProtocolError::Packet(err)
  }
  guard self.routing.lookup(info.dst) is Some(peer_id) else {
    raise ProtocolError::UnroutableDestination(info.dst)
  }
  let pkts = self.peers[peer_id].encapsulate(inner_ip, now_ms)
  (peer_id, pkts)
}

///|
/// Process an inbound WireGuard UDP datagram across all peers on this `Device`, enforcing `CookieReply` under load
/// and §4 Cryptokey Routing reverse-path source IP verification on decrypted inner packets.
/// Returns `(peer_id_or_neg1_for_cookie, action, flushed_datagrams)`.
pub fn Device::receive_wire(
  self : Device,
  wire_bytes : BytesView,
  now_ms : UInt64,
  under_load~ : Bool = false,
  peer_endpoint_bytes~ : BytesView = b"",
) -> (Int32, TunnelAction, Array[Bytes]) raise ProtocolError {
  let parsed = @packet.parse_wire_packet(wire_bytes) catch {
    err => raise ProtocolError::Packet(err)
  }
  match parsed {
    Initiation(init_msg) => {
      if !verify_initiation_mac1(init_msg, self.local_static_public) {
        raise ProtocolError::InvalidMac1
      }
      if under_load &&
        !self.cookies.verify_initiation_mac2(
          init_msg, peer_endpoint_bytes, now_ms,
        ) {
        let reply = self.cookies.create_cookie_reply(
          init_msg.sender_index,
          init_msg.mac1,
          peer_endpoint_bytes,
          now_ms,
        )
        let wire = reply.encode() catch {
          err => raise ProtocolError::Packet(err)
        }
        return (-1, SendWirePacket(wire), [])
      }
      let consumed = consume_handshake_initiation(
        init_msg,
        self.local_static_private,
      )
      let mut found_peer = -1
      for i, p in self.peers {
        if @crypto.ct_eq(
            p.remote_static_public,
            consumed.initiator_static_public,
          ) {
          found_peer = i
        }
      }
      if found_peer < 0 {
        raise ProtocolError::UnknownPeer(consumed.initiator_static_public)
      }
      let (act, flushed) = self.peers[found_peer].decapsulate(
        wire_bytes, now_ms,
      )
      (found_peer, act, flushed)
    }
    Response(r) => {
      let peer_id = self.find_peer_by_index(r.receiver_index)
      let (act, flushed) = self.peers[peer_id].decapsulate(
        wire_bytes,
        now_ms,
        under_load~,
        cookie_validator=self.cookies,
        peer_endpoint_bytes~,
      )
      (peer_id, act, flushed)
    }
    Cookie(c) => {
      let peer_id = self.find_peer_by_index(c.receiver_index)
      let (act, flushed) = self.peers[peer_id].decapsulate(wire_bytes, now_ms)
      (peer_id, act, flushed)
    }
    Transport(t) => {
      let peer_id = self.find_peer_by_index(t.receiver_index)
      let (act, flushed) = self.peers[peer_id].decapsulate(wire_bytes, now_ms)
      match act {
        DeliverInnerPacket(inner_ip~, ..) => {
          let info = @packet.inspect_and_trim_inner_ip(inner_ip) catch {
            err => raise ProtocolError::Packet(err)
          }
          if !self.routing.verify_source(info.src, peer_id) {
            raise ProtocolError::InvalidSourceIp(info.src)
          }
          (peer_id, act, flushed)
        }
        _ => (peer_id, act, flushed)
      }
    }
  }
}

///|
fn Device::find_peer_by_index(
  self : Device,
  receiver_index : UInt32,
) -> Int32 raise ProtocolError {
  for i, p in self.peers {
    if p.owns_receiver_index(receiver_index) {
      return i
    }
  }
  raise ProtocolError::UnknownReceiverIndex(receiver_index)
}

///|
/// Tick timers across all peers on this `Device`, returning `(peer_id, wire_datagram)` pairs to send.
pub fn Device::tick_all(
  self : Device,
  now_ms : UInt64,
) -> Array[(Int32, Bytes)] raise ProtocolError {
  let out : Array[(Int32, Bytes)] = []
  for i, p in self.peers {
    let pkts = p.tick(now_ms)
    for pkt in pkts {
      out.push((i, pkt))
    }
  }
  out
}