///|
/// WireGuard §6 timer & counter constants (milliseconds).
pub const REKEY_AFTER_TIME_MS : UInt64 = 120_000UL

///|
pub const REJECT_AFTER_TIME_MS : UInt64 = 180_000UL

///|
pub const REKEY_TIMEOUT_MS : UInt64 = 5_000UL

///|
pub const REKEY_ATTEMPT_TIME_MS : UInt64 = 90_000UL

///|
pub const KEEPALIVE_TIMEOUT_MS : UInt64 = 10_000UL

///|
pub const REKEY_AFTER_MESSAGES : UInt64 = 0xffffffffffff0000UL

///|
/// Active transport session slot holding directional keys, counters, creation timestamp, and RFC 6479 replay window.
#derive(Debug, Eq)
pub struct TransportSession {
  local_index : UInt32
  remote_index : UInt32
  send_key : Bytes
  recv_key : Bytes
  is_initiator : Bool
  created_ms : UInt64
  mut send_counter : UInt64
  replay : @replay.ReplayWindow
}

///|
fn TransportSession::from_derived(
  keys : DerivedSessionKeys,
  now_ms : UInt64,
) -> TransportSession {
  {
    local_index: keys.local_index,
    remote_index: keys.remote_index,
    send_key: keys.send_key,
    recv_key: keys.recv_key,
    is_initiator: keys.is_initiator,
    created_ms: now_ms,
    send_counter: 0UL,
    replay: @replay.ReplayWindow::new(),
  }
}

///|
fn TransportSession::is_expired(
  self : TransportSession,
  now_ms : UInt64,
) -> Bool {
  now_ms >= self.created_ms && now_ms - self.created_ms >= REJECT_AFTER_TIME_MS
}

///|
/// Result emitted by `PeerTunnel` when processing inbound UDP packets or timer ticks.
#derive(Debug, Eq)
pub(all) enum TunnelAction {
  NoOp
  SendWirePacket(Bytes)
  DeliverInnerPacket(inner_ip~ : Bytes, response_wire~ : Bytes?)
  ReceivedKeepalive(response_wire~ : Bytes?)
  HandshakeCompleted(response_wire~ : Bytes?)
}

///|
/// Sans-IO WireGuard single-peer state machine managing handshakes, 3-slot key rotation (`previous` / `current` / `next`),
/// RFC 6479 anti-replay, `TAI64N` monotonic timestamps, Cookie Reply caching, and §6 timers.
pub struct PeerTunnel {
  local_static_private : Bytes
  local_static_public : Bytes
  remote_static_public : Bytes
  preshared_key : Bytes?
  persistent_keepalive_ms : UInt64?
  priv mut prng_state : Bytes
  priv mut next_index : UInt32
  priv mut pending_handshake : InitiatorHandshake?
  priv mut handshake_started_ms : UInt64?
  priv mut last_handshake_sent_ms : UInt64?
  priv mut last_sent_mac1 : Bytes?
  priv mut cached_cookie : (Bytes, UInt64)?
  priv mut greatest_peer_timestamp : Tai64n?
  priv mut last_local_unix_sec : UInt64
  priv mut last_local_nanos : UInt32
  priv mut current_session : TransportSession?
  priv mut previous_session : TransportSession?
  priv mut next_session : TransportSession?
  priv mut last_tx_ms : UInt64?
  priv mut last_rx_data_ms : UInt64?
  priv mut awaiting_passive_keepalive : Bool
  priv staged_outbound : Array[Bytes]
}

///|
/// Construct a deterministic, Sans-IO `PeerTunnel` with a 32-byte `entropy_seed`.
pub fn PeerTunnel::new(
  local_static_private : BytesView,
  remote_static_public : BytesView,
  entropy_seed : BytesView,
  initial_index~ : UInt32 = 1U,
  preshared_key? : BytesView,
  persistent_keepalive_ms? : UInt64,
) -> PeerTunnel raise ProtocolError {
  ensure_key32("local_static_private", local_static_private)
  ensure_key32("remote_static_public", remote_static_public)
  ensure_key32("entropy_seed", entropy_seed)
  let local_static_public = @crypto.x25519_public_key(local_static_private) catch {
    err => raise ProtocolError::Crypto(err)
  }
  let psk_opt = match preshared_key {
    None => None
    Some(q) => {
      ensure_key32("preshared_key", q)
      Some(q.to_owned())
    }
  }
  {
    local_static_private: local_static_private.to_owned(),
    local_static_public,
    remote_static_public: remote_static_public.to_owned(),
    preshared_key: psk_opt,
    persistent_keepalive_ms,
    prng_state: entropy_seed.to_owned(),
    next_index: if initial_index == 0U {
      1U
    } else {
      initial_index
    },
    pending_handshake: None,
    handshake_started_ms: None,
    last_handshake_sent_ms: None,
    last_sent_mac1: None,
    cached_cookie: None,
    greatest_peer_timestamp: None,
    last_local_unix_sec: 1_700_000_000UL,
    last_local_nanos: 0U,
    current_session: None,
    previous_session: None,
    next_session: None,
    last_tx_ms: None,
    last_rx_data_ms: None,
    awaiting_passive_keepalive: false,
    staged_outbound: [],
  }
}

///|
fn PeerTunnel::next_ephemeral_key(self : PeerTunnel) -> Bytes {
  let (next_state, out_key) = @crypto.kdf2(self.prng_state, b"ephemeral")
  self.prng_state = next_state
  out_key
}

///|
fn PeerTunnel::alloc_index(self : PeerTunnel) -> UInt32 {
  let idx = self.next_index
  let next = idx + 1U
  self.next_index = if next == 0U { 1U } else { next }
  idx
}

///|
fn PeerTunnel::next_monotonic_tai64n(
  self : PeerTunnel,
  now_ms : UInt64,
) -> Tai64n {
  let sec = 1_700_000_000UL + now_ms / 1000UL
  let ns = (now_ms % 1000UL * 1_000_000UL).to_uint()
  if sec < self.last_local_unix_sec ||
    (sec == self.last_local_unix_sec && ns <= self.last_local_nanos) {
    if self.last_local_nanos + 1U < 1_000_000_000U {
      self.last_local_nanos = self.last_local_nanos + 1U
    } else {
      self.last_local_unix_sec = self.last_local_unix_sec + 1UL
      self.last_local_nanos = 0U
    }
  } else {
    self.last_local_unix_sec = sec
    self.last_local_nanos = ns
  }
  ignore(ns)
  Tai64n::from_unix(self.last_local_unix_sec, self.last_local_nanos)
}

///|
fn PeerTunnel::valid_cookie(self : PeerTunnel, now_ms : UInt64) -> Bytes? {
  match self.cached_cookie {
    None => None
    Some((ck, born_ms)) =>
      if now_ms >= born_ms && now_ms - born_ms < COOKIE_REFRESH_MS {
        Some(ck)
      } else {
        self.cached_cookie = None
        None
      }
  }
}

///|
/// Return `true` if there is a currently non-expired established `TransportSession`.
pub fn PeerTunnel::has_established_session(
  self : PeerTunnel,
  now_ms : UInt64,
) -> Bool {
  match self.current_session {
    Some(s) => !s.is_expired(now_ms)
    None => false
  }
}

///|
/// Return the active local session receiver index (and next/previous indices) owned by this peer.
pub fn PeerTunnel::owns_receiver_index(self : PeerTunnel, idx : UInt32) -> Bool {
  let in_pending = match self.pending_handshake {
    Some(hs) => hs.local_index == idx
    None => false
  }
  let in_curr = match self.current_session {
    Some(s) => s.local_index == idx
    None => false
  }
  let in_prev = match self.previous_session {
    Some(s) => s.local_index == idx
    None => false
  }
  let in_next = match self.next_session {
    Some(s) => s.local_index == idx
    None => false
  }
  in_pending || in_curr || in_prev || in_next
}

///|
/// Explicitly initiate a `HandshakeInitiation` wire frame (148 bytes) at `now_ms`.
pub fn PeerTunnel::initiate_handshake(
  self : PeerTunnel,
  now_ms : UInt64,
) -> Bytes raise ProtocolError {
  let eph = self.next_ephemeral_key()
  let idx = self.alloc_index()
  let ts = self.next_monotonic_tai64n(now_ms)
  let ck_opt = self.valid_cookie(now_ms)
  let (msg, hs) = match (self.preshared_key, ck_opt) {
    (Some(psk), Some(ck)) =>
      create_handshake_initiation(
        self.local_static_private,
        self.remote_static_public,
        eph,
        idx,
        ts,
        preshared_key=psk,
        cookie=ck,
      )
    (Some(psk), None) =>
      create_handshake_initiation(
        self.local_static_private,
        self.remote_static_public,
        eph,
        idx,
        ts,
        preshared_key=psk,
      )
    (None, Some(ck)) =>
      create_handshake_initiation(
        self.local_static_private,
        self.remote_static_public,
        eph,
        idx,
        ts,
        cookie=ck,
      )
    (None, None) =>
      create_handshake_initiation(
        self.local_static_private,
        self.remote_static_public,
        eph,
        idx,
        ts,
      )
  }
  if self.handshake_started_ms is None {
    self.handshake_started_ms = Some(now_ms)
  }
  self.pending_handshake = Some(hs)
  self.last_handshake_sent_ms = Some(now_ms)
  self.last_sent_mac1 = Some(msg.mac1)
  msg.encode() catch {
    err => raise ProtocolError::Packet(err)
  }
}

///|
fn PeerTunnel::purge_expired_sessions(
  self : PeerTunnel,
  now_ms : UInt64,
) -> Unit {
  match self.current_session {
    Some(s) if s.is_expired(now_ms) => self.current_session = None
    _ => ()
  }
  match self.previous_session {
    Some(s) if s.is_expired(now_ms) => self.previous_session = None
    _ => ()
  }
  match self.next_session {
    Some(s) if s.is_expired(now_ms) => self.next_session = None
    _ => ()
  }
}

///|
fn PeerTunnel::should_rekey_on_send(
  self : PeerTunnel,
  s : TransportSession,
  now_ms : UInt64,
) -> Bool {
  if self.pending_handshake is Some(_) {
    false
  } else if s.send_counter >= REKEY_AFTER_MESSAGES {
    true
  } else if s.is_initiator &&
    now_ms >= s.created_ms &&
    now_ms - s.created_ms >= REKEY_AFTER_TIME_MS {
    true
  } else {
    false
  }
}

///|
fn PeerTunnel::seal_with_current(
  self : PeerTunnel,
  inner_or_empty : BytesView,
  now_ms : UInt64,
) -> Bytes raise ProtocolError {
  guard self.current_session is Some(sess) else {
    raise ProtocolError::NoActiveSession
  }
  if sess.is_expired(now_ms) {
    self.current_session = None
    raise ProtocolError::NoActiveSession
  }
  if sess.send_counter >= @replay.REJECT_AFTER_MESSAGES {
    raise ProtocolError::CounterExhausted
  }
  let counter = sess.send_counter
  sess.send_counter = counter + 1UL
  let pkt = seal_transport_packet(
    sess.remote_index,
    sess.send_key,
    counter,
    inner_or_empty,
  )
  self.last_tx_ms = Some(now_ms)
  self.awaiting_passive_keepalive = false
  pkt.encode() catch {
    err => raise ProtocolError::Packet(err)
  }
}

///|
/// Encapsulate an outbound inner IPv4/IPv6 packet into one or more outbound WireGuard UDP datagrams.
/// If no active session exists yet, queues the packet (bounded to 16 packets) and emits a `HandshakeInitiation`.
/// If the active session has crossed `REKEY_AFTER_TIME_MS` (120s) or `REKEY_AFTER_MESSAGES`, emits both the encrypted
/// transport packet AND a background rekey `HandshakeInitiation`.
pub fn PeerTunnel::encapsulate(
  self : PeerTunnel,
  inner_ip : BytesView,
  now_ms : UInt64,
) -> Array[Bytes] raise ProtocolError {
  let _ = @packet.inspect_and_trim_inner_ip(inner_ip) catch {
    err => raise ProtocolError::Packet(err)
  }
  self.purge_expired_sessions(now_ms)
  match self.current_session {
    None => {
      if self.staged_outbound.length() >= 16 {
        let _ = self.staged_outbound.remove(0)
      }
      self.staged_outbound.push(inner_ip.to_owned())
      let should_send_hs = match self.last_handshake_sent_ms {
        None => true
        Some(last_ms) =>
          now_ms >= last_ms && now_ms - last_ms >= REKEY_TIMEOUT_MS
      }
      if should_send_hs {
        [self.initiate_handshake(now_ms)]
      } else {
        []
      }
    }
    Some(sess) => {
      let out : Array[Bytes] = []
      let data_wire = self.seal_with_current(inner_ip, now_ms)
      out.push(data_wire)
      if self.should_rekey_on_send(sess, now_ms) {
        out.push(self.initiate_handshake(now_ms))
      }
      out
    }
  }
}

///|
fn PeerTunnel::flush_staged_packets(
  self : PeerTunnel,
  now_ms : UInt64,
) -> Array[Bytes] raise ProtocolError {
  let out : Array[Bytes] = []
  while self.staged_outbound.length() > 0 {
    let p = self.staged_outbound.remove(0)
    out.push(self.seal_with_current(p, now_ms))
  }
  out
}

///|
/// Decapsulate an inbound WireGuard UDP datagram at `now_ms`.
/// Optionally accepts `cookie_validator` + `under_load` + `peer_endpoint_bytes` to enforce `mac2` Cookie Reply under DoS load.
pub fn PeerTunnel::decapsulate(
  self : PeerTunnel,
  wire_bytes : BytesView,
  now_ms : UInt64,
  under_load~ : Bool = false,
  cookie_validator? : CookieValidator,
  peer_endpoint_bytes~ : BytesView = b"",
) -> (TunnelAction, Array[Bytes]) raise ProtocolError {
  self.purge_expired_sessions(now_ms)
  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 {
        if cookie_validator is Some(cv) {
          if !cv.verify_initiation_mac2(init_msg, peer_endpoint_bytes, now_ms) {
            let reply = cv.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 (SendWirePacket(wire), [])
          }
        }
      }
      let consumed = consume_handshake_initiation(
        init_msg,
        self.local_static_private,
      )
      if !@crypto.ct_eq(
          consumed.initiator_static_public,
          self.remote_static_public,
        ) {
        raise ProtocolError::UnknownPeer(consumed.initiator_static_public)
      }
      match self.greatest_peer_timestamp {
        Some(prev_ts) =>
          if !consumed.timestamp.is_newer_than(prev_ts) {
            raise ProtocolError::ReplayedOrStaleTimestamp
          }
        None => ()
      }
      self.greatest_peer_timestamp = Some(consumed.timestamp)

      let eph = self.next_ephemeral_key()
      let resp_idx = self.alloc_index()
      let ck_opt = self.valid_cookie(now_ms)
      let (resp_msg, keys) = match (self.preshared_key, ck_opt) {
        (Some(psk), Some(ck)) =>
          create_handshake_response(
            consumed,
            eph,
            resp_idx,
            preshared_key=psk,
            cookie=ck,
          )
        (Some(psk), None) =>
          create_handshake_response(consumed, eph, resp_idx, preshared_key=psk)
        (None, Some(ck)) =>
          create_handshake_response(consumed, eph, resp_idx, cookie=ck)
        (None, None) => create_handshake_response(consumed, eph, resp_idx)
      }
      // Key confirmation (§5.4.5): stage Responder session in `next_session` until first valid TransportData arrives
      self.next_session = Some(TransportSession::from_derived(keys, now_ms))
      self.last_sent_mac1 = Some(resp_msg.mac1)
      let resp_wire = resp_msg.encode() catch {
        err => raise ProtocolError::Packet(err)
      }
      (HandshakeCompleted(response_wire=Some(resp_wire)), [])
    }
    Response(resp_msg) => {
      if !verify_response_mac1(resp_msg, self.local_static_public) {
        raise ProtocolError::InvalidMac1
      }
      if under_load {
        if cookie_validator is Some(cv) {
          if !cv.verify_response_mac2(resp_msg, peer_endpoint_bytes, now_ms) {
            let reply = cv.create_cookie_reply(
              resp_msg.sender_index,
              resp_msg.mac1,
              peer_endpoint_bytes,
              now_ms,
            )
            let wire = reply.encode() catch {
              err => raise ProtocolError::Packet(err)
            }
            return (SendWirePacket(wire), [])
          }
        }
      }
      guard self.pending_handshake is Some(hs) else {
        raise ProtocolError::UnexpectedHandshakeResponse(
          resp_msg.receiver_index,
        )
      }
      let keys = consume_handshake_response(hs, resp_msg)
      self.pending_handshake = None
      self.handshake_started_ms = None
      self.last_handshake_sent_ms = None
      self.previous_session = self.current_session
      self.current_session = Some(TransportSession::from_derived(keys, now_ms))
      let flushed = self.flush_staged_packets(now_ms)
      // If no staged data was sent, send an immediate 0-byte keepalive for key confirmation on responder (§5.4.5)
      if flushed.length() == 0 {
        let confirm_ka = self.seal_with_current(b"", now_ms)
        (HandshakeCompleted(response_wire=Some(confirm_ka)), [])
      } else {
        (HandshakeCompleted(response_wire=None), flushed)
      }
    }
    Cookie(cookie_msg) => {
      guard self.last_sent_mac1 is Some(mac1) else { return (NoOp, []) }
      let ck = consume_cookie_reply(cookie_msg, self.remote_static_public, mac1)
      self.cached_cookie = Some((ck, now_ms))
      (NoOp, [])
    }
    Transport(data_msg) => {
      // Match session slot (`current`, `next` with key-confirmation promotion, or `previous`)
      let mut promote_next = false
      let target_sess = match self.current_session {
        Some(s) if s.local_index == data_msg.receiver_index => Some(s)
        _ =>
          match self.next_session {
            Some(ns) if ns.local_index == data_msg.receiver_index => {
              promote_next = true
              Some(ns)
            }
            _ =>
              match self.previous_session {
                Some(ps) if ps.local_index == data_msg.receiver_index =>
                  Some(ps)
                _ => None
              }
          }
      }
      guard target_sess is Some(sess) else {
        raise ProtocolError::UnknownReceiverIndex(data_msg.receiver_index)
      }
      // Phase 1: read-only anti-replay pre-check before AEAD decryption
      if !sess.replay.check(data_msg.counter) {
        raise ProtocolError::ReplayedOrTooOldPacket(data_msg.counter)
      }
      let inner = open_transport_packet(sess.recv_key, data_msg)
      // Phase 2: commit sequence number after AEAD succeeds
      if !sess.replay.accept(data_msg.counter) {
        raise ProtocolError::ReplayedOrTooOldPacket(data_msg.counter)
      }
      let flushed : Array[Bytes] = if promote_next {
        self.previous_session = self.current_session
        self.current_session = Some(sess)
        self.next_session = None
        self.flush_staged_packets(now_ms)
      } else {
        []
      }
      if inner.length() == 0 {
        (ReceivedKeepalive(response_wire=None), flushed)
      } else {
        self.last_rx_data_ms = Some(now_ms)
        self.awaiting_passive_keepalive = true
        (DeliverInnerPacket(inner_ip=inner, response_wire=None), flushed)
      }
    }
  }
}

///|
/// Advance WireGuard §6 protocol timers at `now_ms`, returning any wire frames that must be transmitted
/// (handshake retransmission, passive keepalive, persistent keepalive, or session expiration cleanup).
pub fn PeerTunnel::tick(
  self : PeerTunnel,
  now_ms : UInt64,
) -> Array[Bytes] raise ProtocolError {
  self.purge_expired_sessions(now_ms)
  let out : Array[Bytes] = []

  // 1. Handshake retry / attempt timeout (§6.4)
  if self.pending_handshake is Some(_) {
    if self.handshake_started_ms is Some(start_ms) {
      if now_ms >= start_ms && now_ms - start_ms >= REKEY_ATTEMPT_TIME_MS {
        self.pending_handshake = None
        self.handshake_started_ms = None
        self.last_handshake_sent_ms = None
        self.staged_outbound.clear()
      } else if self.last_handshake_sent_ms is Some(last_ms) {
        if now_ms >= last_ms && now_ms - last_ms >= REKEY_TIMEOUT_MS {
          out.push(self.initiate_handshake(now_ms))
        }
      }
    }
  }

  // 2. Passive Keepalive (§6.5: received data, sent nothing for 10s)
  if self.awaiting_passive_keepalive && self.current_session is Some(_) {
    if self.last_rx_data_ms is Some(rx_ms) {
      if now_ms >= rx_ms && now_ms - rx_ms >= KEEPALIVE_TIMEOUT_MS {
        out.push(self.seal_with_current(b"", now_ms))
      }
    }
  }

  // 3. Persistent Keepalive (NAT traversal)
  if self.persistent_keepalive_ms is Some(interval_ms) && interval_ms > 0UL {
    if self.current_session is Some(_) {
      let due = match self.last_tx_ms {
        None => true
        Some(tx_ms) => now_ms >= tx_ms && now_ms - tx_ms >= interval_ms
      }
      if due && out.length() == 0 {
        out.push(self.seal_with_current(b"", now_ms))
      }
    }
  }

  out
}