///|
/// Parsed WireGuard key material supporting both:
/// 1. Standard Wireshark `wg.keylog_file` (`LOCAL_STATIC_PRIVATE_KEY = ...`, `LOCAL_EPHEMERAL_PRIVATE_KEY = ...`, etc.)
/// 2. Kernel probe session keylogs (`STAT`/`TIME`/`EMPT` + `0x `).
#derive(Debug, Eq)
pub struct KeyLog {
  static_private_keys : Array[Bytes]
  static_public_keys : Array[Bytes]
  ephemeral_private_keys : Array[Bytes]
  preshared_keys : Array[Bytes]
  direct_traffic_keys : Map[UInt32, Bytes]
  handshake_stage_keys : Map[(String, UInt32), (Bytes, Bytes)]
}

///|
pub fn KeyLog::empty() -> KeyLog {
  {
    static_private_keys: [],
    static_public_keys: [],
    ephemeral_private_keys: [],
    preshared_keys: [],
    direct_traffic_keys: Map([]),
    handshake_stage_keys: Map([]),
  }
}

///|
fn try_pub_key(priv_k : BytesView) -> Bytes? {
  Some(@crypto.x25519_public_key(priv_k)) catch {
    _ => None
  }
}

///|
fn try_dh(priv_k : BytesView, pub_k : BytesView) -> Bytes? {
  Some(@crypto.x25519_dh(priv_k, pub_k)) catch {
    _ => None
  }
}

///|
fn try_aead_open(
  k : BytesView,
  counter : UInt64,
  ct : BytesView,
  aad : BytesView,
) -> Bytes? {
  Some(@crypto.wg_aead_open(k, counter, ct, aad)) catch {
    _ => None
  }
}

///|
fn try_consume_init(
  m : @packet.HandshakeInitiation,
  s_priv : BytesView,
) -> @protocol.ConsumedInitiation? {
  Some(@protocol.consume_handshake_initiation(m, s_priv)) catch {
    _ => None
  }
}

///|
fn try_open_transport(k : BytesView, m : @packet.TransportData) -> Bytes? {
  Some(@protocol.open_transport_packet(k, m)) catch {
    _ => None
  }
}

///|
fn trim_line(s : StringView) -> StringView {
  let mut a = 0
  let mut b = s.length()
  while a < b && (s[a] == ' ' || s[a] == '\t' || s[a] == '\r' || s[a] == 0xfeff) {
    a = a + 1
  }
  while b > a &&
        (
          s[b - 1] == ' ' ||
          s[b - 1] == '\t' ||
          s[b - 1] == '\r' ||
          s[b - 1] == 0xfeff
        ) {
    b = b - 1
  }
  s[a:b]
}

///|
fn split_spaces(s : StringView) -> Array[StringView] {
  let out : Array[StringView] = []
  let mut i = 0
  let n = s.length()
  while i < n {
    while i < n && (s[i] == ' ' || s[i] == '\t') {
      i = i + 1
    }
    if i < n {
      let start = i
      while i < n && s[i] != ' ' && s[i] != '\t' {
        i = i + 1
      }
      out.push(s[start:i])
    }
  }
  out
}

///|
fn parse_hex_u32(tok : StringView) -> UInt32? {
  let body = if tok.length() > 2 &&
    tok[0] == '0' &&
    (tok[1] == 'x' || tok[1] == 'X') {
    tok[2:]
  } else {
    tok
  }
  if body.length() == 0 || body.length() > 8 {
    return None
  }
  let mut acc = 0U
  for i in 0..= '0' && ch <= '9' {
      (ch.to_int() - '0'.to_int()).reinterpret_as_uint()
    } else if ch >= 'a' && ch <= 'f' {
      (ch.to_int() - 'a'.to_int() + 10).reinterpret_as_uint()
    } else if ch >= 'A' && ch <= 'F' {
      (ch.to_int() - 'A'.to_int() + 10).reinterpret_as_uint()
    } else {
      return None
    }
    acc = (acc << 4) | nib
  }
  Some(acc)
}

///|
fn add_unique_bytes(arr : Array[Bytes], v : Bytes) -> Unit {
  for x in arr {
    if @crypto.ct_eq(x, v) {
      return
    }
  }
  arr.push(v)
}

///|
/// Parse a WireGuard keylog text (Wireshark `KEY = BASE64` format or `0xINDEX BASE64` session trace format).
pub fn parse_keylog(text : StringView) -> KeyLog raise PcapError {
  let kl = KeyLog::empty()
  let mut pos = 0
  let mut line_no = 0
  let total = text.length()
  while pos <= total {
    let mut nl = pos
    while nl < total && text[nl] != '\n' {
      nl = nl + 1
    }
    line_no = line_no + 1
    let raw = trim_line(text[pos:nl])
    if raw.length() > 0 && raw[0] != '#' {
      let mut eq_pos = -1
      for i in 0.. 0 {
        let name = trim_line(raw[:eq_pos]).to_owned()
        let val_str = trim_line(raw[eq_pos + 1:])
        let key_bytes = @crypto.from_base64(val_str) catch {
          _ =>
            @crypto.from_hex(val_str) catch {
              _ =>
                raise PcapError::InvalidKeylogLine(
                  line=line_no,
                  reason="invalid Base64/Hex key in \{name}",
                )
            }
        }
        if key_bytes.length() != 32 {
          raise PcapError::InvalidKeylogLine(
            line=line_no,
            reason="expected 32-byte key for \{name}",
          )
        }
        match name {
          "LOCAL_STATIC_PRIVATE_KEY" => {
            add_unique_bytes(kl.static_private_keys, key_bytes)
            if try_pub_key(key_bytes) is Some(pub_k) {
              add_unique_bytes(kl.static_public_keys, pub_k)
            }
          }
          "REMOTE_STATIC_PUBLIC_KEY" =>
            add_unique_bytes(kl.static_public_keys, key_bytes)
          "LOCAL_EPHEMERAL_PRIVATE_KEY" =>
            add_unique_bytes(kl.ephemeral_private_keys, key_bytes)
          "PRESHARED_KEY" => add_unique_bytes(kl.preshared_keys, key_bytes)
          _ => ()
        }
      } else {
        let toks = split_spaces(raw)
        if toks.length() == 2 {
          match parse_hex_u32(toks[0]) {
            Some(idx) => {
              let k = @crypto.from_base64(toks[1]) catch {
                _ =>
                  raise PcapError::InvalidKeylogLine(
                    line=line_no,
                    reason="invalid traffic key base64",
                  )
              }
              if k.length() == 32 {
                kl.direct_traffic_keys[idx] = k
              }
            }
            None =>
              raise PcapError::InvalidKeylogLine(
                line=line_no,
                reason="unrecognized 2-token keylog entry",
              )
          }
        } else if toks.length() == 4 {
          let stage = toks[0].to_owned()
          if stage == "STAT" || stage == "TIME" || stage == "EMPT" {
            if parse_hex_u32(toks[1]) is Some(idx) {
              let k = @crypto.from_base64(toks[2]) catch {
                _ =>
                  raise PcapError::InvalidKeylogLine(
                    line=line_no,
                    reason="invalid stage key base64",
                  )
              }
              let aad = @crypto.from_base64(toks[3]) catch {
                _ =>
                  raise PcapError::InvalidKeylogLine(
                    line=line_no,
                    reason="invalid stage AAD base64",
                  )
              }
              kl.handshake_stage_keys[(stage, idx)] = (k, aad)
            }
          }
        }
      }
    }
    if nl >= total {
      break
    }
    pos = nl + 1
  }
  kl
}

///|
/// Format key material in standard Wireshark `wg.keylog_file` syntax.
pub fn format_wireshark_keylog(
  local_static_private : BytesView,
  remote_static_public : BytesView,
  ephemeral_privates : Array[Bytes],
  preshared_key? : BytesView,
) -> String {
  let sb = StringBuilder()
  sb.write_string(
    "LOCAL_STATIC_PRIVATE_KEY = \{@crypto.to_base64(local_static_private)}\n",
  )
  sb.write_string(
    "REMOTE_STATIC_PUBLIC_KEY = \{@crypto.to_base64(remote_static_public)}\n",
  )
  if preshared_key is Some(psk) {
    sb.write_string("PRESHARED_KEY = \{@crypto.to_base64(psk)}\n")
  }
  for eph in ephemeral_privates {
    sb.write_string("LOCAL_EPHEMERAL_PRIVATE_KEY = \{@crypto.to_base64(eph)}\n")
  }
  sb.to_string()
}

///|
/// High-level inspection result for a single WireGuard frame in a PCAP capture.
#derive(Debug, Eq)
pub(all) struct InspectedWireFrame {
  frame_no : Int32
  src : String
  dst : String
  packet_kind : String
  mac1_verified : Bool?
  decrypted_ok : Bool
  detail : String
}

///|
/// Summary of an inspected WireGuard PCAP capture.
#derive(Debug, Eq)
pub(all) struct CaptureAuditSummary {
  total_udp_frames : Int32
  wireguard_frames : Int32
  initiations : Int32
  responses : Int32
  cookie_replies : Int32
  transport_packets : Int32
  decrypted_packets : Int32
  records : Array[InspectedWireFrame]
}

///|
priv struct DerivedHalfHs {
  initiator_static_pub : Bytes
  initiator_eph_pub : Bytes
  initiator_eph_priv : Bytes?
  initiator_static_priv : Bytes?
  chaining_key : Bytes
  hash : Bytes
}

///|
/// Inspect all UDP frames in `pcap_bytes`, dissect WireGuard frames, validate `mac1` when keys are available,
/// derive session keys from `keylog` (if provided), and decrypt inner IPv4/IPv6 payloads.
pub fn inspect_wireguard_pcap(
  pcap_bytes : BytesView,
  keylog? : KeyLog,
) -> CaptureAuditSummary raise PcapError {
  let udp_frames = parse_pcap_udp_frames(pcap_bytes)
  let kl = match keylog {
    Some(k) => k
    None => KeyLog::empty()
  }

  let traffic_keys : Map[UInt32, Bytes] = Map([])
  for idx, k in kl.direct_traffic_keys {
    traffic_keys[idx] = k
  }
  let half_handshakes : Map[UInt32, DerivedHalfHs] = Map([])

  let records : Array[InspectedWireFrame] = []
  let mut wg_count = 0
  let mut init_count = 0
  let mut resp_count = 0
  let mut cookie_count = 0
  let mut data_count = 0
  let mut dec_count = 0

  let psk_candidates : Array[Bytes] = [
    Bytes::from_array(FixedArray::make(32, b'\x00')),
  ]
  for q in kl.preshared_keys {
    add_unique_bytes(psk_candidates, q)
  }

  for f in udp_frames {
    let src_ep = "\{f.src_ip}:\{f.src_port}"
    let dst_ep = "\{f.dst_ip}:\{f.dst_port}"
    let parsed_res : Result[@packet.WirePacket, @packet.PacketError] = Ok(
      @packet.parse_wire_packet(f.udp_payload, strict_reserved=true),
    ) catch {
      err => Err(err)
    }
    match parsed_res {
      Err(_) => ()
      Ok(Initiation(m)) => {
        wg_count = wg_count + 1
        init_count = init_count + 1
        let mut mac1_ok : Bool? = None
        for pub_k in kl.static_public_keys {
          if @protocol.verify_initiation_mac1(m, pub_k) {
            mac1_ok = Some(true)
          } else if mac1_ok is None {
            mac1_ok = Some(false)
          }
        }
        let mut decrypted = false
        let mut detail = "sender_idx=0x\{u32_hex(m.sender_index)}"

        for s_priv in kl.static_private_keys {
          if !decrypted {
            if try_consume_init(m, s_priv) is Some(cons) {
              decrypted = true
              mac1_ok = Some(true)
              let init_pub_b64 = @crypto.to_base64(
                cons.initiator_static_public[:],
              )
              detail = "\{detail} initiator=\{init_pub_b64[:12]}..."
              let mut matched_e_priv : Bytes? = None
              for ep in kl.ephemeral_private_keys {
                if try_pub_key(ep) is Some(ep_pub) &&
                  @crypto.ct_eq(ep_pub, m.unencrypted_ephemeral) {
                  matched_e_priv = Some(ep)
                }
              }
              let mut matched_si_priv : Bytes? = None
              for sp in kl.static_private_keys {
                if try_pub_key(sp) is Some(sp_pub) &&
                  @crypto.ct_eq(sp_pub, cons.initiator_static_public) {
                  matched_si_priv = Some(sp)
                }
              }
              half_handshakes[m.sender_index] = {
                initiator_static_pub: cons.initiator_static_public,
                initiator_eph_pub: m.unencrypted_ephemeral,
                initiator_eph_priv: matched_e_priv,
                initiator_static_priv: matched_si_priv,
                chaining_key: cons.chaining_key,
                hash: cons.hash,
              }
            }
          }
        }

        if !decrypted {
          for e_priv in kl.ephemeral_private_keys {
            if try_pub_key(e_priv) is Some(e_pub) &&
              @crypto.ct_eq(e_pub, m.unencrypted_ephemeral) {
              for s_priv in kl.static_private_keys {
                for r_pub in kl.static_public_keys {
                  if !decrypted {
                    if reconstruct_initiator_half(m, s_priv, r_pub, e_priv)
                      is Some(half) {
                      decrypted = true
                      mac1_ok = Some(true)
                      let init_pub_b64 = @crypto.to_base64(
                        half.initiator_static_pub[:],
                      )
                      detail = "\{detail} initiator=\{init_pub_b64[:12]}..."
                      half_handshakes[m.sender_index] = half
                    }
                  }
                }
              }
            }
          }
        }

        if !decrypted {
          if kl.handshake_stage_keys.get(("STAT", m.sender_index))
            is Some((stat_k, stat_aad)) {
            if try_aead_open(stat_k, 0UL, m.encrypted_static, stat_aad)
              is Some(init_pub) {
              decrypted = true
              add_unique_bytes(kl.static_public_keys, init_pub)
              let b64 = @crypto.to_base64(init_pub[:])
              detail = "\{detail} initiator=\{b64[:12]}..."
            }
          }
        }

        if decrypted {
          dec_count = dec_count + 1
        }
        records.push({
          frame_no: f.frame_no,
          src: src_ep,
          dst: dst_ep,
          packet_kind: "HandshakeInitiation",
          mac1_verified: mac1_ok,
          decrypted_ok: decrypted,
          detail,
        })
      }
      Ok(Response(m)) => {
        wg_count = wg_count + 1
        resp_count = resp_count + 1
        let mut mac1_ok : Bool? = None
        for pub_k in kl.static_public_keys {
          if @protocol.verify_response_mac1(m, pub_k) {
            mac1_ok = Some(true)
          } else if mac1_ok is None {
            mac1_ok = Some(false)
          }
        }
        let mut decrypted = false
        let detail = "sender_idx=0x\{u32_hex(m.sender_index)} receiver_idx=0x\{u32_hex(m.receiver_index)}"

        if half_handshakes.get(m.receiver_index) is Some(half) {
          if derive_from_response(
              half,
              m,
              kl.ephemeral_private_keys,
              psk_candidates,
            )
            is Some((t_init_send, t_resp_send)) {
            decrypted = true
            mac1_ok = Some(true)
            traffic_keys[m.sender_index] = t_init_send
            traffic_keys[m.receiver_index] = t_resp_send
          }
        }
        if !decrypted {
          if kl.handshake_stage_keys.get(("EMPT", m.sender_index))
            is Some((empt_k, empt_aad)) {
            if try_aead_open(empt_k, 0UL, m.encrypted_nothing, empt_aad)
              is Some(_) {
              decrypted = true
            }
          }
        }
        if decrypted {
          dec_count = dec_count + 1
        }
        records.push({
          frame_no: f.frame_no,
          src: src_ep,
          dst: dst_ep,
          packet_kind: "HandshakeResponse",
          mac1_verified: mac1_ok,
          decrypted_ok: decrypted,
          detail,
        })
      }
      Ok(Cookie(m)) => {
        wg_count = wg_count + 1
        cookie_count = cookie_count + 1
        records.push({
          frame_no: f.frame_no,
          src: src_ep,
          dst: dst_ep,
          packet_kind: "CookieReply",
          mac1_verified: None,
          decrypted_ok: false,
          detail: "receiver_idx=0x\{u32_hex(m.receiver_index)}",
        })
      }
      Ok(Transport(m)) => {
        wg_count = wg_count + 1
        data_count = data_count + 1
        let mut decrypted = false
        let mut detail = "receiver_idx=0x\{u32_hex(m.receiver_index)} counter=\{m.counter} (encrypted \{m.encrypted_packet.length()}B)"
        if traffic_keys.get(m.receiver_index) is Some(tkey) {
          if try_open_transport(tkey, m) is Some(inner) {
            decrypted = true
            dec_count = dec_count + 1
            detail = "counter=\{m.counter} -> \{@packet.describe_inner_ip(inner)}"
          }
        }
        records.push({
          frame_no: f.frame_no,
          src: src_ep,
          dst: dst_ep,
          packet_kind: "TransportData",
          mac1_verified: None,
          decrypted_ok: decrypted,
          detail,
        })
      }
    }
  }

  {
    total_udp_frames: udp_frames.length(),
    wireguard_frames: wg_count,
    initiations: init_count,
    responses: resp_count,
    cookie_replies: cookie_count,
    transport_packets: data_count,
    decrypted_packets: dec_count,
    records,
  }
}

///|
fn reconstruct_initiator_half(
  m : @packet.HandshakeInitiation,
  s_i_priv : BytesView,
  s_r_pub : BytesView,
  e_i_priv : BytesView,
) -> DerivedHalfHs? {
  if !@protocol.verify_initiation_mac1(m, s_r_pub) {
    return None
  }
  guard try_pub_key(s_i_priv) is Some(s_i_pub) else { return None }
  let (c0, h0) = @protocol.initial_noise_state()
  let mut c = c0
  let mut h = @crypto.blake2s_256_pair(h0, s_r_pub)
  c = @crypto.kdf1(c, m.unencrypted_ephemeral)
  h = @crypto.blake2s_256_pair(h, m.unencrypted_ephemeral)
  guard try_dh(e_i_priv, s_r_pub) is Some(dh_es) else { return None }
  let (c1, k_es) = @crypto.kdf2(c, dh_es)
  c = c1
  guard try_aead_open(k_es, 0UL, m.encrypted_static, h) is Some(dec_pub) else {
    return None
  }
  if !@crypto.ct_eq(dec_pub, s_i_pub) {
    return None
  }
  h = @crypto.blake2s_256_pair(h, m.encrypted_static)
  guard try_dh(s_i_priv, s_r_pub) is Some(dh_ss) else { return None }
  let (c2, k_ss) = @crypto.kdf2(c, dh_ss)
  c = c2
  guard try_aead_open(k_ss, 0UL, m.encrypted_timestamp, h) is Some(_) else {
    return None
  }
  h = @crypto.blake2s_256_pair(h, m.encrypted_timestamp)
  Some({
    initiator_static_pub: s_i_pub,
    initiator_eph_pub: m.unencrypted_ephemeral,
    initiator_eph_priv: Some(e_i_priv.to_owned()),
    initiator_static_priv: Some(s_i_priv.to_owned()),
    chaining_key: c,
    hash: h,
  })
}

///|
fn derive_from_response(
  half : DerivedHalfHs,
  m : @packet.HandshakeResponse,
  ephemeral_privs : Array[Bytes],
  psks : Array[Bytes],
) -> (Bytes, Bytes)? {
  if half.initiator_eph_priv is Some(e_i_priv) &&
    half.initiator_static_priv is Some(s_i_priv) {
    let mut c = half.chaining_key
    let mut h = half.hash
    c = @crypto.kdf1(c, m.unencrypted_ephemeral)
    h = @crypto.blake2s_256_pair(h, m.unencrypted_ephemeral)
    if try_dh(e_i_priv, m.unencrypted_ephemeral) is Some(dh_ee) {
      c = @crypto.kdf1(c, dh_ee)
      if try_dh(s_i_priv, m.unencrypted_ephemeral) is Some(dh_se) {
        c = @crypto.kdf1(c, dh_se)
        for psk in psks {
          let (c_psk, tau, k_psk) = @crypto.kdf3(c, psk)
          let h_psk = @crypto.blake2s_256_pair(h, tau)
          if try_aead_open(k_psk, 0UL, m.encrypted_nothing, h_psk) is Some(_) {
            return Some(@crypto.kdf2(c_psk, b""))
          }
        }
      }
    }
  }

  for e_r_priv in ephemeral_privs {
    if try_pub_key(e_r_priv) is Some(e_r_pub) &&
      @crypto.ct_eq(e_r_pub, m.unencrypted_ephemeral) {
      let mut c = half.chaining_key
      let mut h = half.hash
      c = @crypto.kdf1(c, m.unencrypted_ephemeral)
      h = @crypto.blake2s_256_pair(h, m.unencrypted_ephemeral)
      if try_dh(e_r_priv, half.initiator_eph_pub) is Some(dh_ee) {
        c = @crypto.kdf1(c, dh_ee)
        if try_dh(e_r_priv, half.initiator_static_pub) is Some(dh_se) {
          c = @crypto.kdf1(c, dh_se)
          for psk in psks {
            let (c_psk, tau, k_psk) = @crypto.kdf3(c, psk)
            let h_psk = @crypto.blake2s_256_pair(h, tau)
            if try_aead_open(k_psk, 0UL, m.encrypted_nothing, h_psk) is Some(_) {
              return Some(@crypto.kdf2(c_psk, b""))
            }
          }
        }
      }
    }
  }
  None
}

///|
fn u32_hex(v : UInt32) -> String {
  let digits = "0123456789abcdef"
  let sb = StringBuilder()
  for i in 0..<8 {
    let shift = (7 - i) * 4
    let nib = ((v >> shift) & 0x0fU).reinterpret_as_int()
    sb.write_char(digits[nib].to_int().unsafe_to_char())
  }
  sb.to_string()
}

///|
pub fn CaptureAuditSummary::format_report(
  self : CaptureAuditSummary,
  max_records~ : Int32 = 25,
) -> String {
  let sb = StringBuilder()
  sb.write_string(
    "PCAP Summary: udp_frames=\{self.total_udp_frames}, wireguard_frames=\{self.wireguard_frames} (init=\{self.initiations}, resp=\{self.responses}, cookie=\{self.cookie_replies}, data=\{self.transport_packets}), decrypted=\{self.decrypted_packets}\n",
  )
  let limit = if self.records.length() < max_records {
    self.records.length()
  } else {
    max_records
  }
  for i in 0.. " [mac1=OK]"
      Some(false) => " [mac1=FAIL]"
      None => ""
    }
    let dec_tag = if r.decrypted_ok { " [DECRYPTED]" } else { "" }
    sb.write_string(
      "  #\{r.frame_no} \{r.src} -> \{r.dst} \{r.packet_kind}\{mac_tag}\{dec_tag}: \{r.detail}\n",
    )
  }
  if self.records.length() > limit {
    sb.write_string(
      "  ... (\{self.records.length() - limit} additional WireGuard frames omitted)\n",
    )
  }
  sb.to_string()
}