///|
/// PartyU or PartyV nonce (RFC 9053). It is a byte string or an integer.
pub(all) enum PartyNonce {
  Bytes(Bytes)
  Int(Int32)
} derive(Eq)

///|
pub extend PartyNonce with Eq::{equal}

///|
#deprecated("Use `!=` instead", skip_current_package=true)
#doc(hidden)
pub extend PartyNonce with Eq::{not_equal}

///|
/// One COSE header map (protected or unprotected).
///
/// `rest` keeps labels this library does not interpret, so a round trip can
/// preserve them. Critical labels in `crit` must be in the known set:
/// alg, crit, content type, kid, IV, partial IV, and the KDF parameters
/// salt, PartyU/PartyV info, ephemeral key, and static key.
pub(all) struct Header {
  alg : CoseAlg?
  crit : Array[Label]
  content_type : ContentType?
  kid : Bytes?
  iv : Bytes?
  partial_iv : Bytes?
  salt : Bytes?
  party_u_id : Bytes?
  party_u_nonce : PartyNonce?
  party_u_other : Bytes?
  party_v_id : Bytes?
  party_v_nonce : PartyNonce?
  party_v_other : Bytes?
  epk : CoseKey?
  static_key : CoseKey?
  static_kid : Bytes?
  rest : Array[(Label, @cbor.CborValue)]
} derive(Eq)

///|
pub extend Header with Eq::{equal}

///|
#deprecated("Use `!=` instead", skip_current_package=true)
#doc(hidden)
pub extend Header with Eq::{not_equal}

///|
/// A header map with no fields.
pub fn Header::empty() -> Header {
  {
    alg: None,
    crit: [],
    content_type: None,
    kid: None,
    iv: None,
    partial_iv: None,
    salt: None,
    party_u_id: None,
    party_u_nonce: None,
    party_u_other: None,
    party_v_id: None,
    party_v_nonce: None,
    party_v_other: None,
    epk: None,
    static_key: None,
    static_kid: None,
    rest: [],
  }
}

///|
/// An otherwise empty header whose alg is `alg`.
pub fn Header::with_alg(alg : CoseAlg) -> Header {
  { ..Header::empty(), alg: Some(alg.normalize()), }
}

///|
/// Reject a crit list that contains a label this library does not understand.
pub fn Header::check_crit(self : Header) -> Unit raise CoseError {
  for i = 0; i < self.crit.length(); i = i + 1 {
    let label = self.crit[i]
    if !label_is_known(label) {
      raise BadStructure("critical header is not understood")
    }
  }
}

///|
fn expect_bytes(
  value : @cbor.CborValue,
  what : String,
) -> Bytes raise CoseError {
  match cbor_unwrap(value) {
    @cbor.Bytes(b) => b
    _ => raise BadStructure("\{what} must be a byte string")
  }
}

///|
fn party_nonce_from(
  value : @cbor.CborValue,
  what : String,
) -> PartyNonce raise CoseError {
  match cbor_unwrap(value) {
    @cbor.Bytes(b) => PartyNonce::Bytes(b)
    @cbor.Integer(n) => PartyNonce::Int(int_from_i64(n))
    @cbor.Unsigned(n) =>
      if n > 2147483647UL {
        raise BadStructure("\{what} integer is too large")
      } else {
        PartyNonce::Int(n.to_int())
      }
    _ => raise BadStructure("\{what} must be a byte string or an integer")
  }
}

///|
fn party_nonce_to_cbor(nonce : PartyNonce) -> @cbor.CborValue {
  match nonce {
    PartyNonce::Bytes(b) => @cbor.Bytes(b)
    PartyNonce::Int(n) => @cbor.Integer(n.to_int64())
  }
}

///|
fn seen_label(seen : Array[Label], label : Label) -> Bool {
  for i = 0; i < seen.length(); i = i + 1 {
    if seen[i] == label {
      return true
    }
  }
  false
}

///|
/// Read a header map. Duplicate labels are an error.
pub fn Header::from_cbor(value : @cbor.CborValue) -> Header raise CoseError {
  match cbor_unwrap(value) {
    @cbor.Map(pairs) => {
      let mut alg = None
      let mut crit = []
      let mut content_type = None
      let mut kid = None
      let mut iv = None
      let mut partial_iv = None
      let mut salt = None
      let mut party_u_id = None
      let mut party_u_nonce = None
      let mut party_u_other = None
      let mut party_v_id = None
      let mut party_v_nonce = None
      let mut party_v_other = None
      let mut epk = None
      let mut static_key = None
      let mut static_kid = None
      let rest : Array[(Label, @cbor.CborValue)] = []
      let seen : Array[Label] = []
      for i = 0; i < pairs.length(); i = i + 1 {
        let label = Label::from_cbor(pairs[i].0)
        if seen_label(seen, label) {
          raise BadStructure("duplicate header label")
        }
        seen.push(label)
        let item = pairs[i].1
        match label {
          Label::Int(1) => alg = Some(CoseAlg::from_cbor(item))
          Label::Int(2) => crit = crit_from_cbor(item)
          Label::Int(3) => content_type = Some(ContentType::from_cbor(item))
          Label::Int(4) => kid = Some(expect_bytes(item, "kid"))
          Label::Int(5) => iv = Some(expect_bytes(item, "IV"))
          Label::Int(6) => partial_iv = Some(expect_bytes(item, "partial IV"))
          Label::Int(-1) => epk = Some(CoseKey::from_cbor(item))
          Label::Int(-2) => static_key = Some(CoseKey::from_cbor(item))
          Label::Int(-3) =>
            static_kid = Some(expect_bytes(item, "static key id"))
          Label::Int(-20) => salt = Some(expect_bytes(item, "salt"))
          Label::Int(-21) =>
            party_u_id = Some(expect_bytes(item, "PartyU identity"))
          Label::Int(-22) =>
            party_u_nonce = Some(party_nonce_from(item, "PartyU nonce"))
          Label::Int(-23) =>
            party_u_other = Some(expect_bytes(item, "PartyU other"))
          Label::Int(-24) =>
            party_v_id = Some(expect_bytes(item, "PartyV identity"))
          Label::Int(-25) =>
            party_v_nonce = Some(party_nonce_from(item, "PartyV nonce"))
          Label::Int(-26) =>
            party_v_other = Some(expect_bytes(item, "PartyV other"))
          _ => rest.push((label, item))
        }
      }
      let header : Header = {
        alg,
        crit,
        content_type,
        kid,
        iv,
        partial_iv,
        salt,
        party_u_id,
        party_u_nonce,
        party_u_other,
        party_v_id,
        party_v_nonce,
        party_v_other,
        epk,
        static_key,
        static_kid,
        rest,
      }
      header.check_crit()
      header
    }
    _ => raise BadStructure("header is not a map")
  }
}

///|
fn crit_from_cbor(value : @cbor.CborValue) -> Array[Label] raise CoseError {
  match cbor_unwrap(value) {
    @cbor.Array(items) => {
      if items.length() == 0 {
        raise BadStructure("crit array must not be empty")
      }
      let out : Array[Label] = []
      for i = 0; i < items.length(); i = i + 1 {
        out.push(Label::from_cbor(items[i]))
      }
      out
    }
    _ => raise BadStructure("crit must be an array of labels")
  }
}

///|
/// Build the CBOR map for this header. The encoder sorts keys.
pub fn Header::to_cbor(self : Header) -> @cbor.CborValue {
  let pairs : Array[(@cbor.CborValue, @cbor.CborValue)] = []
  match self.alg {
    Some(alg) => pairs.push((@cbor.Integer(1L), alg.to_cbor()))
    None => ()
  }
  if self.crit.length() > 0 {
    let labels : Array[@cbor.CborValue] = []
    for i = 0; i < self.crit.length(); i = i + 1 {
      labels.push(self.crit[i].to_cbor())
    }
    pairs.push((@cbor.Integer(2L), @cbor.Array(labels)))
  }
  match self.content_type {
    Some(ct) => pairs.push((@cbor.Integer(3L), ct.to_cbor()))
    None => ()
  }
  match self.kid {
    Some(kid) => pairs.push((@cbor.Integer(4L), @cbor.Bytes(kid)))
    None => ()
  }
  match self.iv {
    Some(iv) => pairs.push((@cbor.Integer(5L), @cbor.Bytes(iv)))
    None => ()
  }
  match self.partial_iv {
    Some(piv) => pairs.push((@cbor.Integer(6L), @cbor.Bytes(piv)))
    None => ()
  }
  match self.epk {
    Some(key) => pairs.push((@cbor.Integer(-1L), key.to_cbor()))
    None => ()
  }
  match self.static_key {
    Some(key) => pairs.push((@cbor.Integer(-2L), key.to_cbor()))
    None => ()
  }
  match self.static_kid {
    Some(kid) => pairs.push((@cbor.Integer(-3L), @cbor.Bytes(kid)))
    None => ()
  }
  match self.salt {
    Some(salt) => pairs.push((@cbor.Integer(-20L), @cbor.Bytes(salt)))
    None => ()
  }
  match self.party_u_id {
    Some(id) => pairs.push((@cbor.Integer(-21L), @cbor.Bytes(id)))
    None => ()
  }
  match self.party_u_nonce {
    Some(nonce) => pairs.push((@cbor.Integer(-22L), party_nonce_to_cbor(nonce)))
    None => ()
  }
  match self.party_u_other {
    Some(other) => pairs.push((@cbor.Integer(-23L), @cbor.Bytes(other)))
    None => ()
  }
  match self.party_v_id {
    Some(id) => pairs.push((@cbor.Integer(-24L), @cbor.Bytes(id)))
    None => ()
  }
  match self.party_v_nonce {
    Some(nonce) => pairs.push((@cbor.Integer(-25L), party_nonce_to_cbor(nonce)))
    None => ()
  }
  match self.party_v_other {
    Some(other) => pairs.push((@cbor.Integer(-26L), @cbor.Bytes(other)))
    None => ()
  }
  for i = 0; i < self.rest.length(); i = i + 1 {
    pairs.push((self.rest[i].0.to_cbor(), self.rest[i].1))
  }
  @cbor.Map(pairs)
}

///|
/// Encode this header map with deterministic CBOR (RFC 8949 section 4.2).
pub fn Header::encode(self : Header) -> Bytes {
  @cbor.encode(self.to_cbor())
}

///|
/// Protected header bucket: the raw `bstr` bytes are what Sig_structure,
/// MAC_structure, and Enc_structure commit to. An empty bstr is an empty map.
pub(all) struct Protected {
  raw : Bytes
  header : Header
} derive(Eq)

///|
pub extend Protected with Eq::{equal}

///|
#deprecated("Use `!=` instead", skip_current_package=true)
#doc(hidden)
pub extend Protected with Eq::{not_equal}

///|
/// Encode `header`. An empty map becomes a zero-length bstr.
pub fn Protected::from_header(header : Header) -> Protected raise CoseError {
  header.check_crit()
  let encoded = header.encode()
  // RFC 9052 allows either `h''` or `h'a0'` for an empty header map.
  // Creation uses the zero-length form so it matches the cose-wg examples.
  if encoded.length() == 1 && encoded[0] == b'\xa0' {
    { raw: bytes_empty(), header, }
  } else {
    { raw: encoded, header, }
  }
}

///|
/// Keep `raw` for signing and also parse it as a header map.
pub fn Protected::from_raw(raw : Bytes) -> Protected raise CoseError {
  if raw.length() == 0 {
    { raw, header: Header::empty(), }
  } else {
    let header = Header::from_cbor(decode_cbor(raw))
    { raw, header, }
  }
}

///|
fn occupied_labels(header : Header) -> Array[Label] {
  let out : Array[Label] = []
  if header.alg is Some(_) {
    out.push(Label::Int(1))
  }
  if header.crit.length() > 0 {
    out.push(Label::Int(2))
  }
  if header.content_type is Some(_) {
    out.push(Label::Int(3))
  }
  if header.kid is Some(_) {
    out.push(Label::Int(4))
  }
  if header.iv is Some(_) {
    out.push(Label::Int(5))
  }
  if header.partial_iv is Some(_) {
    out.push(Label::Int(6))
  }
  if header.epk is Some(_) {
    out.push(Label::Int(-1))
  }
  if header.static_key is Some(_) {
    out.push(Label::Int(-2))
  }
  if header.static_kid is Some(_) {
    out.push(Label::Int(-3))
  }
  if header.salt is Some(_) {
    out.push(Label::Int(-20))
  }
  if header.party_u_id is Some(_) {
    out.push(Label::Int(-21))
  }
  if header.party_u_nonce is Some(_) {
    out.push(Label::Int(-22))
  }
  if header.party_u_other is Some(_) {
    out.push(Label::Int(-23))
  }
  if header.party_v_id is Some(_) {
    out.push(Label::Int(-24))
  }
  if header.party_v_nonce is Some(_) {
    out.push(Label::Int(-25))
  }
  if header.party_v_other is Some(_) {
    out.push(Label::Int(-26))
  }
  for i = 0; i < header.rest.length(); i = i + 1 {
    out.push(header.rest[i].0)
  }
  out
}

///|
/// RFC 9052 section 3: a label may appear in only one of the two buckets.
fn reject_shared_header_labels(
  prot : Header,
  unprot : Header,
) -> Unit raise CoseError {
  let left = occupied_labels(prot)
  let right = occupied_labels(unprot)
  for i = 0; i < left.length(); i = i + 1 {
    for j = 0; j < right.length(); j = j + 1 {
      if left[i] == right[j] {
        raise BadStructure(
          "header label appears in both protected and unprotected headers",
        )
      }
    }
  }
}

///|
/// Read alg from the protected header, then the unprotected header. Differing values are an error.
pub fn resolve_alg(prot : Header, unprot : Header) -> CoseAlg raise CoseError {
  match (prot.alg, unprot.alg) {
    (Some(a), Some(b)) => {
      let left = a.normalize()
      let right = b.normalize()
      if left != right {
        raise AlgMismatch(
          "protected alg \{left.name()} does not match unprotected alg \{right.name()}",
        )
      }
      left
    }
    (Some(a), None) => a.normalize()
    (None, Some(b)) => b.normalize()
    (None, None) => raise BadStructure("missing alg header")
  }
}

///|
fn check_key_alg(
  key_alg : CoseAlg?,
  header_alg : CoseAlg,
) -> Unit raise CoseError {
  match key_alg {
    Some(alg) => {
      let key = alg.normalize()
      let header = header_alg.normalize()
      if key != header {
        raise AlgMismatch(
          "key alg \{key.name()} does not match header alg \{header.name()}",
        )
      }
    }
    None => ()
  }
}