///|
/// RFC 9420 §7.5 & §7.6 TreeKEM: private node key store, UpdatePath creation,
/// UpdatePath merging, parent-hash recomputation, and path-secret decryption.

///|
/// Local member's TreeKEM private state: leaf index, leaf encryption private key,
/// signature private key, and private HPKE keys for ancestor nodes on its direct path.
pub struct PrivateTreeState {
  leaf_index : UInt32
  mut leaf_encryption_priv : Bytes
  signature_priv : Bytes
  node_privs : Map[UInt32, Bytes]
}

///|
pub fn PrivateTreeState::new(
  leaf_index : UInt32,
  leaf_encryption_priv : Bytes,
  signature_priv : Bytes,
) -> PrivateTreeState {
  { leaf_index, leaf_encryption_priv, signature_priv, node_privs: {}, }
}

///|
pub fn PrivateTreeState::copy(self : PrivateTreeState) -> PrivateTreeState {
  let m : Map[UInt32, Bytes] = Map([])
  for k, v in self.node_privs {
    m[k] = v
  }
  {
    leaf_index: self.leaf_index,
    leaf_encryption_priv: self.leaf_encryption_priv,
    signature_priv: self.signature_priv,
    node_privs: m,
  }
}

///|
/// Derive a node's HPKE `(priv, pub)` pair from its `path_secret` (RFC 9420 §7.5).
pub fn derive_node_key_pair(
  suite : @types.CipherSuite,
  path_secret : Bytes,
) -> (Bytes, Bytes) raise @types.MlsError {
  let node_secret = @crypto.derive_secret(suite, path_secret, "node")
  @crypto.kem_derive_key_pair(suite, node_secret)
}

///|
pub fn PrivateTreeState::set_leaf_encryption_priv(
  self : PrivateTreeState,
  new_sk : Bytes,
) -> Unit {
  self.leaf_encryption_priv = new_sk
}

///|
pub fn PrivateTreeState::set_node_priv(
  self : PrivateTreeState,
  node : UInt32,
  sk : Bytes,
) -> Unit {
  self.node_privs[node] = sk
}

///|
pub fn PrivateTreeState::clear_node_privs(self : PrivateTreeState) -> Unit {
  self.node_privs.clear()
}

///|
/// Set private key for `node` derived from `path_secret`.
pub fn PrivateTreeState::set_path_secret(
  self : PrivateTreeState,
  suite : @types.CipherSuite,
  node : UInt32,
  path_secret : Bytes,
) -> Unit raise @types.MlsError {
  let (sk, _) = derive_node_key_pair(suite, path_secret)
  self.node_privs[node] = sk
}

///|
/// Lookup our private HPKE key for `node` (leaf or ancestor parent node).
pub fn PrivateTreeState::private_key_for_node(
  self : PrivateTreeState,
  node : UInt32,
) -> Bytes? {
  if node == @treemath.leaf_to_node(self.leaf_index) {
    Some(self.leaf_encryption_priv)
  } else {
    self.node_privs.get(node)
  }
}

///|
/// Result of creating an UpdatePath (RFC 9420 §7.6).
pub struct CreatedUpdatePath {
  update_path : @types.UpdatePath
  path_secrets : Array[Bytes] // one per filtered_direct_path node
  commit_secret : Bytes
  new_tree : RatchetTree
  new_private_state : PrivateTreeState
}

///|
/// Result of processing a received UpdatePath (RFC 9420 §7.6).
pub struct ProcessedUpdatePath {
  decrypted_path_secret : Bytes // path secret at LCA
  commit_secret : Bytes
  new_tree : RatchetTree
  new_private_state : PrivateTreeState
}

///|
/// Merge a received `UpdatePath` from `sender_leaf` into a copy of `tree`,
/// verifying leaf signature, filtered direct path length, and top-down parent hash.
pub fn RatchetTree::merge_update_path(
  self : RatchetTree,
  suite : @types.CipherSuite,
  group_id : Bytes,
  sender_leaf : UInt32,
  update_path : @types.UpdatePath,
) -> RatchetTree raise @types.MlsError {
  // 1. LeafNode source MUST be Commit(parent_hash) and signature MUST verify.
  let leaf_ph = match update_path.leaf_node.leaf_node_source {
    Commit(ph) => ph
    _ =>
      raise @types.MlsError(
        "UpdatePath leaf_node_source must be Commit(parent_hash)",
      )
  }
  verify_leaf_signature(
    suite,
    update_path.leaf_node,
    Some(group_id),
    Some(sender_leaf),
  )

  let next = self.copy()
  let fdp = next.filtered_direct_path(sender_leaf)
  if fdp.length() != update_path.nodes.length() {
    raise @types.MlsError(
      "UpdatePath nodes count (\{update_path.nodes.length()}) != filtered direct path length (\{fdp.length()})",
    )
  }

  // Blank the entire direct path of sender first (RFC 9420 §7.6).
  let sender_node = @treemath.leaf_to_node(sender_leaf)
  for p in @treemath.direct_path(sender_node, next.n_leaves()) {
    next.nodes[p.reinterpret_as_int()] = None
  }

  // Compute parent hashes top-down along the filtered direct path.
  let m = fdp.length()
  let parent_hashes : Array[Bytes] = Array::make(m, b"")
  let mut cur_ph = b""
  for rev = 0; rev < m; rev = rev + 1 {
    let idx = m - 1 - rev
    parent_hashes[idx] = cur_ph
    let (_, copath_node) = fdp[idx]
    let copath_hash = next.node_tree_hash(suite, copath_node)
    cur_ph = compute_parent_hash(
      suite,
      update_path.nodes[idx].encryption_key,
      parent_hashes[idx],
      copath_hash,
    )
  }

  // Verify the leaf node's committed parent_hash matches the top-down chain!
  if !@crypto.constant_time_eq(leaf_ph, cur_ph) {
    raise @types.MlsError("UpdatePath leaf parent_hash mismatch")
  }

  // Install new parent nodes (empty unmerged_leaves) and new leaf node.
  for i = 0; i < m; i = i + 1 {
    let (parent_node, _) = fdp[i]
    next.nodes[parent_node.reinterpret_as_int()] = Some(
      Parent({
        encryption_key: update_path.nodes[i].encryption_key,
        parent_hash: parent_hashes[i],
        unmerged_leaves: [],
      }),
    )
  }
  next.nodes[sender_node.reinterpret_as_int()] = Some(
    Leaf(update_path.leaf_node),
  )
  next
}

///|
/// Process a received `UpdatePath` as member `priv_state.leaf_index`.
/// `build_group_context(new_tree_hash)` builds the provisional GroupContext bytes
/// used as HPKE context when decrypting `UpdatePathNode`.
pub fn RatchetTree::process_update_path(
  self : RatchetTree,
  suite : @types.CipherSuite,
  group_id : Bytes,
  sender_leaf : UInt32,
  update_path : @types.UpdatePath,
  excluded_leaves : Array[UInt32],
  priv_state : PrivateTreeState,
  build_group_context : (Bytes) -> Bytes raise @types.MlsError,
) -> ProcessedUpdatePath raise @types.MlsError {
  if sender_leaf == priv_state.leaf_index {
    raise @types.MlsError("cannot process own UpdatePath as receiver")
  }
  let fdp = self.filtered_direct_path(sender_leaf)
  let new_tree = self.merge_update_path(
    suite, group_id, sender_leaf, update_path,
  )
  let new_tree_hash = new_tree.tree_hash(suite)
  let ctx_bytes = build_group_context(new_tree_hash)

  // Find LCA of sender and receiver on sender's filtered direct path.
  let sender_node = @treemath.leaf_to_node(sender_leaf)
  let my_node = @treemath.leaf_to_node(priv_state.leaf_index)
  let lca = @treemath.common_ancestor(sender_node, my_node, self.n_leaves())
  let mut lca_idx = -1
  for i = 0; i < fdp.length(); i = i + 1 {
    let (p, _) = fdp[i]
    if p == lca {
      lca_idx = i
      break
    }
  }
  if lca_idx < 0 {
    raise @types.MlsError(
      "LCA node \{lca} not present on sender filtered direct path",
    )
  }

  let (_, lca_copath) = fdp[lca_idx]
  // Resolution of lca_copath in the PRE-merge tree, excluding newly added leaves.
  let raw_res = self.resolution(lca_copath)
  let filtered_res : Array[UInt32] = []
  for node in raw_res {
    let is_excl = match @treemath.node_to_leaf(node) {
      Some(li) => array_contains_uint(excluded_leaves, li)
      None => false
    }
    if !is_excl {
      filtered_res.push(node)
    }
  }

  let up_node = update_path.nodes[lca_idx]
  if up_node.encrypted_path_secret.length() != filtered_res.length() {
    raise @types.MlsError(
      "UpdatePathNode ciphertext count (\{up_node.encrypted_path_secret.length()}) != copath resolution (\{filtered_res.length()})",
    )
  }

  // Locate our node in filtered_res (either our leaf or an ancestor on our direct path).
  let mut ct_idx = -1
  let mut my_priv : Bytes? = None
  for i = 0; i < filtered_res.length(); i = i + 1 {
    let target = filtered_res[i]
    match priv_state.private_key_for_node(target) {
      Some(sk) => {
        ct_idx = i
        my_priv = Some(sk)
        break
      }
      None => ()
    }
  }
  let dec_priv = match my_priv {
    Some(sk) => sk
    None =>
      raise @types.MlsError(
        "no matching private key found in copath resolution for leaf \{priv_state.leaf_index}",
      )
  }
  let ct = up_node.encrypted_path_secret[ct_idx]
  let decrypted_ps = @crypto.decrypt_with_label(
    suite,
    dec_priv,
    "UpdatePathNode",
    ctx_bytes,
    ct.kem_output,
    ct.ciphertext,
  )

  // Walk up filtered_direct_path from lca_idx to root, verifying every derived public key!
  let next_priv = priv_state.copy()
  let mut ps = decrypted_ps
  for i = lca_idx; i < fdp.length(); i = i + 1 {
    let (p_node, _) = fdp[i]
    let (sk, pk) = derive_node_key_pair(suite, ps)
    if !@crypto.constant_time_eq(pk, update_path.nodes[i].encryption_key) {
      raise @types.MlsError(
        "derived UpdatePath public key mismatch at node \{p_node}",
      )
    }
    next_priv.node_privs[p_node] = sk
    ps = @crypto.derive_secret(suite, ps, "path")
  }
  {
    decrypted_path_secret: decrypted_ps,
    commit_secret: ps,
    new_tree,
    new_private_state: next_priv,
  }
}

///|
/// Create a fresh `UpdatePath` from `priv_state.leaf_index` (RFC 9420 §7.6).
/// `leaf_secret` is the fresh N_h-byte leaf secret; `hpke_seed` seeds deterministic
/// ephemeral HPKE encryptions for each copath ciphertext.
pub fn RatchetTree::create_update_path(
  self : RatchetTree,
  suite : @types.CipherSuite,
  group_id : Bytes,
  priv_state : PrivateTreeState,
  leaf_secret : Bytes,
  hpke_seed : Bytes,
  excluded_leaves : Array[UInt32],
  build_group_context : (Bytes) -> Bytes raise @types.MlsError,
) -> CreatedUpdatePath raise @types.MlsError {
  let sender_leaf = priv_state.leaf_index
  let old_leaf = match self.leaf_at(sender_leaf) {
    Some(l) => l
    None => raise @types.MlsError("committer leaf \{sender_leaf} is blank")
  }

  let (new_leaf_sk, new_leaf_pk) = derive_node_key_pair(suite, leaf_secret)
  let fdp = self.filtered_direct_path(sender_leaf)
  let m = fdp.length()

  // Derive path_secrets and (sk, pk) along filtered_direct_path.
  let path_secrets : Array[Bytes] = []
  let node_sks : Array[Bytes] = []
  let node_pks : Array[Bytes] = []
  let mut ps = @crypto.derive_secret(suite, leaf_secret, "path")
  for i = 0; i < m; i = i + 1 {
    path_secrets.push(ps)
    let (sk, pk) = derive_node_key_pair(suite, ps)
    node_sks.push(sk)
    node_pks.push(pk)
    ps = @crypto.derive_secret(suite, ps, "path")
  }
  let commit_secret = ps

  // Prepare merged tree & compute parent hashes top-down.
  let new_tree = self.copy()
  let sender_node = @treemath.leaf_to_node(sender_leaf)
  for p in @treemath.direct_path(sender_node, new_tree.n_leaves()) {
    new_tree.nodes[p.reinterpret_as_int()] = None
  }

  let parent_hashes : Array[Bytes] = Array::make(m, b"")
  let mut cur_ph = b""
  for rev = 0; rev < m; rev = rev + 1 {
    let idx = m - 1 - rev
    parent_hashes[idx] = cur_ph
    let (_, copath_node) = fdp[idx]
    let copath_hash = new_tree.node_tree_hash(suite, copath_node)
    cur_ph = compute_parent_hash(
      suite,
      node_pks[idx],
      parent_hashes[idx],
      copath_hash,
    )
  }

  // Construct & sign the Commit LeafNode.
  let unsigned_leaf : @types.LeafNode = {
    encryption_key: new_leaf_pk,
    signature_key: old_leaf.signature_key,
    credential: old_leaf.credential,
    capabilities: old_leaf.capabilities,
    leaf_node_source: Commit(cur_ph),
    extensions: old_leaf.extensions,
    signature: b"",
  }
  let leaf_tbs = @codec.encode_leaf_node_tbs(
    unsigned_leaf,
    Some(group_id),
    Some(sender_leaf),
  )
  let leaf_sig = @crypto.sign_with_label(
    suite,
    priv_state.signature_priv,
    "LeafNodeTBS",
    leaf_tbs,
  )
  let signed_leaf : @types.LeafNode = { ..unsigned_leaf, signature: leaf_sig, }

  // Install new parent nodes and leaf into new_tree to compute new_tree_hash.
  for i = 0; i < m; i = i + 1 {
    let (p_node, _) = fdp[i]
    new_tree.nodes[p_node.reinterpret_as_int()] = Some(
      Parent({
        encryption_key: node_pks[i],
        parent_hash: parent_hashes[i],
        unmerged_leaves: [],
      }),
    )
  }
  new_tree.nodes[sender_node.reinterpret_as_int()] = Some(Leaf(signed_leaf))
  let new_tree_hash = new_tree.tree_hash(suite)
  let ctx_bytes = build_group_context(new_tree_hash)

  // Encrypt path_secrets to each node in the filtered copath resolution.
  let up_nodes : Array[@types.UpdatePathNode] = []
  let mut enc_counter = 0
  for i = 0; i < m; i = i + 1 {
    let (_, copath_node) = fdp[i]
    let raw_res = self.resolution(copath_node)
    let cts : Array[@types.HPKECiphertext] = []
    for target in raw_res {
      let is_excl = match @treemath.node_to_leaf(target) {
        Some(li) => array_contains_uint(excluded_leaves, li)
        None => false
      }
      if !is_excl {
        let target_pk = self.node_encryption_key(target)
        let eph = @crypto.deterministic_bytes(
          suite,
          hpke_seed,
          "upn-\{enc_counter}",
          suite.kem_secret_len(),
        )
        enc_counter = enc_counter + 1
        cts.push(
          @crypto.encrypt_with_label(
            suite,
            target_pk,
            "UpdatePathNode",
            ctx_bytes,
            path_secrets[i],
            eph,
          ),
        )
      }
    }
    up_nodes.push({ encryption_key: node_pks[i], encrypted_path_secret: cts, })
  }

  let next_priv = priv_state.copy()
  next_priv.leaf_encryption_priv = new_leaf_sk
  next_priv.node_privs.clear()
  for i = 0; i < m; i = i + 1 {
    let (p_node, _) = fdp[i]
    next_priv.node_privs[p_node] = node_sks[i]
  }
  {
    update_path: { leaf_node: signed_leaf, nodes: up_nodes, },
    path_secrets,
    commit_secret,
    new_tree,
    new_private_state: next_priv,
  }
}