///|
fn prefer_bytes(left : Bytes?, right : Bytes?) -> Bytes? {
  match left {
    Some(value) => Some(value)
    None => right
  }
}

///|
fn prefer_nonce(left : PartyNonce?, right : PartyNonce?) -> PartyNonce? {
  match left {
    Some(value) => Some(value)
    None => right
  }
}

///|
fn prefer_key(left : CoseKey?, right : CoseKey?) -> CoseKey? {
  match left {
    Some(value) => Some(value)
    None => right
  }
}

///|
fn cbor_bytes_or_null(value : Bytes?) -> @cbor.CborValue {
  match value {
    Some(bytes) => @cbor.Bytes(bytes)
    None => @cbor.Simple(22)
  }
}

///|
fn cbor_nonce_or_null(value : PartyNonce?) -> @cbor.CborValue {
  match value {
    Some(nonce) => party_nonce_to_cbor(nonce)
    None => @cbor.Simple(22)
  }
}

///|
/// COSE_KDF_Context (RFC 9053 §5.2), encoded with definite lengths.
fn cose_kdf_context(
  alg : CoseAlg,
  prot : Header,
  unprot : Header,
  protected_raw : Bytes,
  key_bits : Int32,
  supp_pub : Bytes?,
  supp_priv : Bytes?,
) -> Bytes {
  let party_u = @cbor.Array([
    cbor_bytes_or_null(prefer_bytes(prot.party_u_id, unprot.party_u_id)),
    cbor_nonce_or_null(prefer_nonce(prot.party_u_nonce, unprot.party_u_nonce)),
    cbor_bytes_or_null(prefer_bytes(prot.party_u_other, unprot.party_u_other)),
  ])
  let party_v = @cbor.Array([
    cbor_bytes_or_null(prefer_bytes(prot.party_v_id, unprot.party_v_id)),
    cbor_nonce_or_null(prefer_nonce(prot.party_v_nonce, unprot.party_v_nonce)),
    cbor_bytes_or_null(prefer_bytes(prot.party_v_other, unprot.party_v_other)),
  ])
  let supp : Array[@cbor.CborValue] = [
    @cbor.Integer(key_bits.to_int64()),
    @cbor.Bytes(protected_raw),
  ]
  match supp_pub {
    Some(other) => supp.push(@cbor.Bytes(other))
    None => ()
  }
  let context : Array[@cbor.CborValue] = [
    alg.to_cbor(),
    party_u,
    party_v,
    @cbor.Array(supp),
  ]
  match supp_priv {
    Some(other) => context.push(@cbor.Bytes(other))
    None => ()
  }
  @cbor.encode(@cbor.Array(context))
}

///|
fn require_kdf_uniqueness(
  prot : Header,
  unprot : Header,
) -> Unit raise CoseError {
  let salt = prefer_bytes(prot.salt, unprot.salt)
  let nonce = prefer_nonce(prot.party_u_nonce, unprot.party_u_nonce)
  if salt is None && nonce is None {
    raise BadStructure("HKDF requires salt or PartyU nonce")
  }
}

///|
fn hkdf_aes_expand(
  prk : Bytes,
  info : Bytes,
  length : Int32,
) -> Bytes raise CoseError {
  if length <= 0 || length > 255 * 16 {
    raise BadStructure("HKDF output length is outside RFC 5869 limits")
  }
  let mut okm = bytes_empty()
  let mut previous = bytes_empty()
  let mut counter : Int32 = 1
  while okm.length() < length {
    let message = bytes_concat(
      bytes_concat(previous, info),
      Bytes::make(1, counter.to_byte()),
    )
    previous = aes_cbc_mac(prk, message, 16)
    okm = bytes_concat(okm, previous)
    counter = counter + 1
  }
  bytes_slice(okm, 0, length)
}

///|
fn hkdf_length(length : Int32) -> Int32 {
  length
}

///|
/// HKDF from a shared secret. SHA-256 and SHA-512 use RFC 5869 extract and
/// expand. The AES variants skip extract, so salt is not mixed in; uniqueness
/// has to come from the context (RFC 9053 §5.1).
fn hkdf_okm(
  alg : CoseAlg,
  salt : Bytes?,
  ikm : Bytes,
  info : Bytes,
  length : Int32,
) -> Bytes raise CoseError {
  let salt_bytes = match salt {
    Some(value) => value
    None => bytes_empty()
  }
  match alg.normalize() {
    CoseAlg::DirectHkdfSha256
    | CoseAlg::EcdhEsHkdf256
    | CoseAlg::EcdhSsHkdf256
    | CoseAlg::EcdhEsA128Kw
    | CoseAlg::EcdhEsA192Kw
    | CoseAlg::EcdhEsA256Kw
    | CoseAlg::EcdhSsA128Kw
    | CoseAlg::EcdhSsA192Kw
    | CoseAlg::EcdhSsA256Kw =>
      @lib.hkdf_sha256(salt_bytes, ikm, info, hkdf_length(length))
    CoseAlg::DirectHkdfSha512
    | CoseAlg::EcdhEsHkdf512
    | CoseAlg::EcdhSsHkdf512 =>
      @lib.hkdf_sha512(salt_bytes, ikm, info, hkdf_length(length))
    CoseAlg::DirectHkdfAes128 => {
      require_len(ikm, 16, "direct+HKDF-AES-128 secret")
      hkdf_aes_expand(ikm, info, length)
    }
    CoseAlg::DirectHkdfAes256 => {
      require_len(ikm, 32, "direct+HKDF-AES-256 secret")
      hkdf_aes_expand(ikm, info, length)
    }
    other => raise UnsupportedAlg(other.name())
  }
}

///|
fn derive_key_ops(key : CoseKey, private : Bool) -> Unit raise CoseError {
  let ops = match key {
    CoseKey::Okp(okp) => okp.key_ops
    CoseKey::Ec2(ec2) => ec2.key_ops
    CoseKey::Sym(sym) => sym.key_ops
    CoseKey::Rsa(rsa) => rsa.key_ops
  }
  if ops.length() == 0 {
    return
  }
  if !private {
    raise BadStructure("public ECDH key_ops must be empty")
  }
  for i = 0; i < ops.length(); i = i + 1 {
    if ops[i] == 7 || ops[i] == 8 {
      return
    }
  }
  raise BadStructure("key_ops does not allow key derivation")
}

///|
fn ecdh_curve_len(crv : Int32) -> Int32 raise CoseError {
  match crv {
    4 => 32
    5 => 56
    1 => raise UnsupportedAlg("ECDH P-256")
    2 => raise UnsupportedAlg("ECDH P-384")
    3 => raise UnsupportedAlg("ECDH P-521")
    _ => raise AlgMismatch("ECDH requires an X25519 or X448 key")
  }
}

///|
fn ecdh_scalar(key : CoseKey) -> (Int32, Bytes) raise CoseError {
  match key {
    CoseKey::Okp(okp) => {
      let size = ecdh_curve_len(okp.crv)
      match okp.d {
        Some(scalar) => {
          require_len(scalar, size, "ECDH scalar")
          (okp.crv, scalar)
        }
        None => raise BadStructure("ECDH private key is missing d")
      }
    }
    CoseKey::Ec2(ec2) => {
      let _len = ecdh_curve_len(ec2.crv)
      raise AlgMismatch("ECDH requires an OKP key")
    }
    _ => raise AlgMismatch("ECDH requires an OKP key")
  }
}

///|
fn ecdh_public_coord(key : CoseKey) -> (Int32, Bytes) raise CoseError {
  match key {
    CoseKey::Okp(okp) => {
      let size = ecdh_curve_len(okp.crv)
      if okp.x.length() == size {
        (okp.crv, okp.x)
      } else {
        let (crv, scalar) = ecdh_scalar(key)
        if crv == 4 {
          (crv, @lib.x25519_public_key(scalar))
        } else {
          (crv, @lib.x448_public_key(scalar))
        }
      }
    }
    CoseKey::Ec2(ec2) => {
      let _len = ecdh_curve_len(ec2.crv)
      raise AlgMismatch("ECDH requires an OKP key")
    }
    _ => raise AlgMismatch("ECDH requires an OKP key")
  }
}

///|
fn ecdh_shared(private_key : CoseKey, peer : CoseKey) -> Bytes raise CoseError {
  let (crv, scalar) = ecdh_scalar(private_key)
  let (peer_crv, peer_u) = ecdh_public_coord(peer)
  if crv != peer_crv {
    raise AlgMismatch("ECDH curves do not match")
  }
  let shared = if crv == 4 {
    match @lib.x25519_or(scalar, peer_u) {
      Ok(value) => value
      Err(_) =>
        raise BadStructure("X25519 scalar and public key must be 32 bytes")
    }
  } else {
    match @lib.x448_or(scalar, peer_u) {
      Ok(value) => value
      Err(_) =>
        raise BadStructure("X448 scalar and public key must be 56 bytes")
    }
  }
  if @lib.dh_shared_is_zero(shared) {
    raise BadStructure("ECDH shared secret is all zeros")
  }
  shared
}

///|
fn ecdh_public_key(private_key : CoseKey) -> CoseKey raise CoseError {
  let (crv, scalar) = ecdh_scalar(private_key)
  let derived = if crv == 4 {
    @lib.x25519_public_key(scalar)
  } else {
    @lib.x448_public_key(scalar)
  }
  match private_key {
    CoseKey::Okp(okp) =>
      if okp.x.length() == derived.length() && !bytes_eq(okp.x, derived) {
        raise BadStructure("ECDH public key does not match the scalar")
      }
    _ => ()
  }
  CoseKey::Okp({
    crv,
    x: derived,
    d: None,
    kid: None,
    alg: None,
    key_ops: [],
    base_iv: None,
  })
}

///|
fn keys_equal_public(left : CoseKey, right : CoseKey) -> Bool raise CoseError {
  let (left_crv, left_x) = ecdh_public_coord(left)
  let (right_crv, right_x) = ecdh_public_coord(right)
  left_crv == right_crv && bytes_eq(left_x, right_x)
}

///|
fn is_hkdf_direct(alg : CoseAlg) -> Bool {
  match alg.normalize() {
    CoseAlg::DirectHkdfSha256
    | CoseAlg::DirectHkdfSha512
    | CoseAlg::DirectHkdfAes128
    | CoseAlg::DirectHkdfAes256 => true
    _ => false
  }
}

///|
fn is_ecdh_direct(alg : CoseAlg) -> Bool {
  match alg.normalize() {
    CoseAlg::EcdhEsHkdf256
    | CoseAlg::EcdhEsHkdf512
    | CoseAlg::EcdhSsHkdf256
    | CoseAlg::EcdhSsHkdf512 => true
    _ => false
  }
}

///|
fn is_ecdh_wrap(alg : CoseAlg) -> Bool {
  match alg.normalize() {
    CoseAlg::EcdhEsA128Kw
    | CoseAlg::EcdhEsA192Kw
    | CoseAlg::EcdhEsA256Kw
    | CoseAlg::EcdhSsA128Kw
    | CoseAlg::EcdhSsA192Kw
    | CoseAlg::EcdhSsA256Kw => true
    _ => false
  }
}

///|
fn is_ephemeral(alg : CoseAlg) -> Bool {
  match alg.normalize() {
    CoseAlg::EcdhEsHkdf256
    | CoseAlg::EcdhEsHkdf512
    | CoseAlg::EcdhEsA128Kw
    | CoseAlg::EcdhEsA192Kw
    | CoseAlg::EcdhEsA256Kw => true
    _ => false
  }
}

///|
fn ecdh_wrap_alg(alg : CoseAlg) -> CoseAlg raise CoseError {
  match alg.normalize() {
    CoseAlg::EcdhEsA128Kw | CoseAlg::EcdhSsA128Kw => CoseAlg::A128KW
    CoseAlg::EcdhEsA192Kw | CoseAlg::EcdhSsA192Kw => CoseAlg::A192KW
    CoseAlg::EcdhEsA256Kw | CoseAlg::EcdhSsA256Kw => CoseAlg::A256KW
    other => raise UnsupportedAlg(other.name())
  }
}

///|
fn ecdh_wrap_len(alg : CoseAlg) -> Int32 raise CoseError {
  match ecdh_wrap_alg(alg) {
    CoseAlg::A128KW => 16
    CoseAlg::A192KW => 24
    CoseAlg::A256KW => 32
    other => raise UnsupportedAlg(other.name())
  }
}

///|
fn kdf_material(
  alg : CoseAlg,
  prot : Header,
  unprot : Header,
  protected_raw : Bytes,
  ikm : Bytes,
  context_alg : CoseAlg,
  key_len : Int32,
  supp_pub : Bytes?,
  supp_priv : Bytes?,
) -> Bytes raise CoseError {
  let info = cose_kdf_context(
    context_alg,
    prot,
    unprot,
    protected_raw,
    key_len * 8,
    supp_pub,
    supp_priv,
  )
  hkdf_okm(alg, prefer_bytes(prot.salt, unprot.salt), ikm, info, key_len)
}