///|
/// Recoverable error raised by any RFC 9420 MLS operation.
pub(all) suberror MlsError {
  MlsError(String)
}

///|
/// RFC 9420 §17.1 ProtocolVersion. Only MLS 1.0 (0x0001) is standardized.
pub const PROTOCOL_VERSION_MLS10 : UInt32 = 1U

///|
/// RFC 9420 §17.1 Cipher Suites supported by MoonMLS.
/// CS1..CS4 and CS6 are fully supported in pure MoonBit via cc06b/mooncry.
#derive(Eq, Debug)
pub(all) enum CipherSuite {
  /// 0x0001: MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519 (MTI)
  MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519
  /// 0x0002: MLS_128_DHKEMP256_AES128GCM_SHA256_P256
  MLS_128_DHKEMP256_AES128GCM_SHA256_P256
  /// 0x0003: MLS_128_DHKEMX25519_CHACHA20POLY1305_SHA256_Ed25519
  MLS_128_DHKEMX25519_CHACHA20POLY1305_SHA256_Ed25519
  /// 0x0004: MLS_256_DHKEMX448_AES256GCM_SHA512_Ed448
  MLS_256_DHKEMX448_AES256GCM_SHA512_Ed448
  /// 0x0006: MLS_256_DHKEMX448_CHACHA20POLY1305_SHA512_Ed448
  MLS_256_DHKEMX448_CHACHA20POLY1305_SHA512_Ed448
}

///|
pub fn CipherSuite::to_u16(self : CipherSuite) -> UInt32 {
  match self {
    MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519 => 1U
    MLS_128_DHKEMP256_AES128GCM_SHA256_P256 => 2U
    MLS_128_DHKEMX25519_CHACHA20POLY1305_SHA256_Ed25519 => 3U
    MLS_256_DHKEMX448_AES256GCM_SHA512_Ed448 => 4U
    MLS_256_DHKEMX448_CHACHA20POLY1305_SHA512_Ed448 => 6U
  }
}

///|
pub fn CipherSuite::from_u16(id : UInt32) -> CipherSuite raise MlsError {
  match id {
    1U => MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519
    2U => MLS_128_DHKEMP256_AES128GCM_SHA256_P256
    3U => MLS_128_DHKEMX25519_CHACHA20POLY1305_SHA256_Ed25519
    4U => MLS_256_DHKEMX448_AES256GCM_SHA512_Ed448
    6U => MLS_256_DHKEMX448_CHACHA20POLY1305_SHA512_Ed448
    _ => raise MlsError("unsupported cipher suite: \{id}")
  }
}

///|
/// Hash digest length Nh (in bytes) for this ciphersuite.
pub fn CipherSuite::hash_len(self : CipherSuite) -> Int32 {
  match self {
    MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519
    | MLS_128_DHKEMP256_AES128GCM_SHA256_P256
    | MLS_128_DHKEMX25519_CHACHA20POLY1305_SHA256_Ed25519 => 32
    MLS_256_DHKEMX448_AES256GCM_SHA512_Ed448
    | MLS_256_DHKEMX448_CHACHA20POLY1305_SHA512_Ed448 => 64
  }
}

///|
/// AEAD key length Nk (in bytes) for this ciphersuite.
pub fn CipherSuite::aead_key_len(self : CipherSuite) -> Int32 {
  match self {
    MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519
    | MLS_128_DHKEMP256_AES128GCM_SHA256_P256 => 16
    MLS_128_DHKEMX25519_CHACHA20POLY1305_SHA256_Ed25519
    | MLS_256_DHKEMX448_AES256GCM_SHA512_Ed448
    | MLS_256_DHKEMX448_CHACHA20POLY1305_SHA512_Ed448 => 32
  }
}

///|
/// AEAD nonce length Nn (in bytes) — 12 bytes for all RFC 9420 suites.
pub fn CipherSuite::aead_nonce_len(self : CipherSuite) -> Int32 {
  ignore(self)
  12
}

///|
/// HPKE KEM private/secret seed length Nsecret (in bytes).
pub fn CipherSuite::kem_secret_len(self : CipherSuite) -> Int32 {
  match self {
    MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519
    | MLS_128_DHKEMP256_AES128GCM_SHA256_P256
    | MLS_128_DHKEMX25519_CHACHA20POLY1305_SHA256_Ed25519 => 32
    MLS_256_DHKEMX448_AES256GCM_SHA512_Ed448
    | MLS_256_DHKEMX448_CHACHA20POLY1305_SHA512_Ed448 => 56
  }
}

///|
/// RFC 9420 §6 WireFormat.
#derive(Eq, Debug)
pub(all) enum WireFormat {
  PublicMessage // 1
  PrivateMessage // 2
  Welcome // 3
  GroupInfo // 4
  KeyPackage // 5
}

///|
pub fn WireFormat::to_u16(self : WireFormat) -> UInt32 {
  match self {
    PublicMessage => 1U
    PrivateMessage => 2U
    Welcome => 3U
    GroupInfo => 4U
    KeyPackage => 5U
  }
}

///|
pub fn WireFormat::from_u16(v : UInt32) -> WireFormat raise MlsError {
  match v {
    1U => PublicMessage
    2U => PrivateMessage
    3U => Welcome
    4U => GroupInfo
    5U => KeyPackage
    _ => raise MlsError("invalid wire format: \{v}")
  }
}

///|
/// RFC 9420 §6 ContentType.
#derive(Eq, Debug)
pub(all) enum ContentType {
  Application // 1
  Proposal // 2
  Commit // 3
}

///|
pub fn ContentType::to_u8(self : ContentType) -> Byte {
  match self {
    Application => b'\x01'
    Proposal => b'\x02'
    Commit => b'\x03'
  }
}

///|
pub fn ContentType::from_u8(v : Byte) -> ContentType raise MlsError {
  match v {
    b'\x01' => Application
    b'\x02' => Proposal
    b'\x03' => Commit
    _ => raise MlsError("invalid content type: \{v.to_int()}")
  }
}

///|
/// RFC 9420 §6 Sender.
#derive(Eq, Debug)
pub(all) enum Sender {
  Member(UInt32) // 1: leaf_index
  External(UInt32) // 2: sender_index
  NewMemberProposal // 3
  NewMemberCommit // 4
}

///|
/// RFC 9420 §5.3 Credential.
#derive(Eq, Debug)
pub(all) enum Credential {
  Basic(Bytes) // credential_type = 1
  X509(Array[Bytes]) // credential_type = 2
}

///|
pub fn Credential::credential_type(self : Credential) -> UInt32 {
  match self {
    Basic(_) => 1U
    X509(_) => 2U
  }
}

///|
/// RFC 9420 §7.2 Extension.
#derive(Eq, Debug)
pub(all) struct Extension {
  extension_type : UInt32 // uint16
  extension_data : Bytes
}

///|
/// Well-known RFC 9420 §17.3 ExtensionType constants.
pub const EXT_APPLICATION_ID : UInt32 = 1U

///|
pub const EXT_RATCHET_TREE : UInt32 = 2U

///|
pub const EXT_REQUIRED_CAPABILITIES : UInt32 = 3U

///|
pub const EXT_EXTERNAL_PUB : UInt32 = 4U

///|
pub const EXT_EXTERNAL_SENDERS : UInt32 = 5U

///|
/// RFC 9420 §7.2 Capabilities.
#derive(Eq, Debug)
pub(all) struct Capabilities {
  versions : Array[UInt32]
  ciphersuites : Array[UInt32]
  extensions : Array[UInt32]
  proposals : Array[UInt32]
  credentials : Array[UInt32]
}

///|
pub fn Capabilities::default_for(suite : CipherSuite) -> Capabilities {
  {
    versions: [PROTOCOL_VERSION_MLS10],
    ciphersuites: [suite.to_u16()],
    extensions: [
      EXT_APPLICATION_ID,
      EXT_RATCHET_TREE,
      EXT_REQUIRED_CAPABILITIES,
      EXT_EXTERNAL_PUB,
      EXT_EXTERNAL_SENDERS,
    ],
    proposals: [],
    credentials: [1U, 2U],
  }
}

///|
/// RFC 9420 §7.2 Lifetime.
#derive(Eq, Debug)
pub(all) struct Lifetime {
  not_before : UInt64
  not_after : UInt64
}

///|
/// RFC 9420 §7.2 LeafNodeSource.
#derive(Eq, Debug)
pub(all) enum LeafNodeSource {
  KeyPackage(Lifetime) // 1
  Update // 2
  Commit(Bytes) // 3: parent_hash
}

///|
/// RFC 9420 §7.2 LeafNode.
#derive(Eq, Debug)
pub(all) struct LeafNode {
  encryption_key : Bytes
  signature_key : Bytes
  credential : Credential
  capabilities : Capabilities
  leaf_node_source : LeafNodeSource
  extensions : Array[Extension]
  signature : Bytes
}

///|
/// RFC 9420 §7.1 ParentNode.
#derive(Eq, Debug)
pub(all) struct ParentNode {
  encryption_key : Bytes
  parent_hash : Bytes
  unmerged_leaves : Array[UInt32]
}

///|
/// RFC 9420 §7.1 Node (optional in ratchet_tree).
#derive(Eq, Debug)
pub(all) enum TreeNode {
  Leaf(LeafNode) // node_type = 1
  Parent(ParentNode) // node_type = 2
}

///|
/// RFC 9420 §5.1.3 HPKECiphertext.
#derive(Eq, Debug)
pub(all) struct HPKECiphertext {
  kem_output : Bytes
  ciphertext : Bytes
}

///|
/// RFC 9420 §10 KeyPackage.
#derive(Eq, Debug)
pub(all) struct KeyPackage {
  version : UInt32
  cipher_suite : UInt32
  init_key : Bytes
  leaf_node : LeafNode
  extensions : Array[Extension]
  signature : Bytes
}

///|
/// RFC 9420 §8.1 GroupContext.
#derive(Eq, Debug)
pub(all) struct GroupContext {
  version : UInt32
  cipher_suite : UInt32
  group_id : Bytes
  epoch : UInt64
  tree_hash : Bytes
  confirmed_transcript_hash : Bytes
  extensions : Array[Extension]
}

///|
/// RFC 9420 §8.4 PreSharedKeyID.
#derive(Eq, Debug)
pub(all) enum PskId {
  External(Bytes) // psktype = 1
  Resumption(UInt32, Bytes, UInt64) // psktype = 2: usage(u8), psk_group_id, psk_epoch
}

///|
#derive(Eq, Debug)
pub(all) struct PreSharedKeyID {
  psk : PskId
  psk_nonce : Bytes
}

///|
/// RFC 9420 §12.1 Proposal.
#derive(Eq, Debug)
pub(all) enum Proposal {
  Add(KeyPackage) // 1
  Update(LeafNode) // 2
  Remove(UInt32) // 3: removed leaf_index
  PreSharedKey(PreSharedKeyID) // 4
  ReInit(Bytes, UInt32, UInt32, Array[Extension]) // 5: group_id, version, cipher_suite, extensions
  ExternalInit(Bytes) // 6: kem_output
  GroupContextExtensions(Array[Extension]) // 7
  Custom(UInt32, Bytes) // unknown/custom proposal_type + raw opaque body
}

///|
/// RFC 9420 §12.4 ProposalOrRef.
#derive(Eq, Debug)
pub(all) enum ProposalOrRef {
  Proposal(Proposal) // 1
  Reference(Bytes) // 2: ProposalRef
}

///|
/// RFC 9420 §7.6 UpdatePathNode & UpdatePath.
#derive(Eq, Debug)
pub(all) struct UpdatePathNode {
  encryption_key : Bytes
  encrypted_path_secret : Array[HPKECiphertext]
}

///|
#derive(Eq, Debug)
pub(all) struct UpdatePath {
  leaf_node : LeafNode
  nodes : Array[UpdatePathNode]
}

///|
/// RFC 9420 §12.4 Commit.
#derive(Eq, Debug)
pub(all) struct Commit {
  proposals : Array[ProposalOrRef]
  path : UpdatePath?
}

///|
/// RFC 9420 §6 FramedContentBody.
#derive(Eq, Debug)
pub(all) enum FramedContentBody {
  Application(Bytes)
  Proposal(Proposal)
  Commit(Commit)
}

///|
pub fn FramedContentBody::content_type(self : FramedContentBody) -> ContentType {
  match self {
    Application(_) => ContentType::Application
    Proposal(_) => ContentType::Proposal
    Commit(_) => ContentType::Commit
  }
}

///|
/// RFC 9420 §6 FramedContent.
#derive(Eq, Debug)
pub(all) struct FramedContent {
  group_id : Bytes
  epoch : UInt64
  sender : Sender
  authenticated_data : Bytes
  body : FramedContentBody
}

///|
/// RFC 9420 §6.1 FramedContentAuthData.
#derive(Eq, Debug)
pub(all) struct FramedContentAuthData {
  signature : Bytes
  confirmation_tag : Bytes? // present iff content_type == commit
}

///|
/// RFC 9420 §6.1 AuthenticatedContent.
#derive(Eq, Debug)
pub(all) struct AuthenticatedContent {
  wire_format : WireFormat
  content : FramedContent
  auth : FramedContentAuthData
}

///|
/// RFC 9420 §6.2 PublicMessage.
#derive(Eq, Debug)
pub(all) struct PublicMessage {
  content : FramedContent
  auth : FramedContentAuthData
  membership_tag : Bytes? // present iff sender == Member(_)
}

///|
/// RFC 9420 §6.3 PrivateMessage.
#derive(Eq, Debug)
pub(all) struct PrivateMessage {
  group_id : Bytes
  epoch : UInt64
  content_type : ContentType
  authenticated_data : Bytes
  encrypted_sender_data : Bytes
  ciphertext : Bytes
}

///|
/// RFC 9420 §6.3.2 MLSSenderData.
#derive(Eq, Debug)
pub(all) struct SenderData {
  leaf_index : UInt32
  generation : UInt32
  reuse_guard : Bytes // 4 bytes
}

///|
/// RFC 9420 §12.4.3.1 GroupInfo, GroupSecrets, EncryptedGroupSecrets, Welcome.
#derive(Eq, Debug)
pub(all) struct GroupInfo {
  group_context : GroupContext
  extensions : Array[Extension]
  confirmation_tag : Bytes
  signer : UInt32
  signature : Bytes
}

///|
#derive(Eq, Debug)
pub(all) struct GroupSecrets {
  joiner_secret : Bytes
  path_secret : Bytes?
  psks : Array[PreSharedKeyID]
}

///|
#derive(Eq, Debug)
pub(all) struct EncryptedGroupSecrets {
  new_member : Bytes // KeyPackageRef
  encrypted_group_secrets : HPKECiphertext
}

///|
#derive(Eq, Debug)
pub(all) struct Welcome {
  cipher_suite : UInt32
  secrets : Array[EncryptedGroupSecrets]
  encrypted_group_info : Bytes
}

///|
/// RFC 9420 §6 Top-level MLSMessage envelope.
#derive(Eq, Debug)
pub(all) enum MLSMessage {
  PublicMessage(PublicMessage)
  PrivateMessage(PrivateMessage)
  Welcome(Welcome)
  GroupInfo(GroupInfo)
  KeyPackage(KeyPackage)
}

///|
pub fn MLSMessage::wire_format(self : MLSMessage) -> WireFormat {
  match self {
    PublicMessage(_) => WireFormat::PublicMessage
    PrivateMessage(_) => WireFormat::PrivateMessage
    Welcome(_) => WireFormat::Welcome
    GroupInfo(_) => WireFormat::GroupInfo
    KeyPackage(_) => WireFormat::KeyPackage
  }
}