///|
/// IETF RFC 9576 / RFC 9577 / RFC 9578 Type `0x0001` Privacy Pass
/// Privately Verifiable Anonymous Tokens built on RFC 9497 VOPRF.
///
/// Enables unlinkable anonymous quota / rate-limit tokens (e.g., AI API
/// anonymous credentials) with issuer DLEQ verifiability and anti-double-spend
/// redemption.

///|
/// RFC 9578 §5 Token Type `0x0001` (VOPRF Privately Verifiable Token).
pub const TOKEN_TYPE_VOPRF : UInt32 = 0x0001U

///|
pub const NONCE_LEN : Int32 = 32

///|
pub const CHALLENGE_DIGEST_LEN : Int32 = 32

///|
pub const TOKEN_KEY_ID_LEN : Int32 = 32

///|
#derive(Debug, Eq)
pub suberror PrivacyPassError {
  InvalidTokenType(UInt32)
  InvalidLength(Int32)
  InvalidChallenge(String)
  KeyIdMismatch
  DoubleSpend
  InvalidAuthenticator
  ChallengeMismatch
  InvalidProof
  EmptyBatch
  VoprfFailed(String)
}

///|
fn voprf_err_str(err : @voprf.VoprfError) -> String {
  match err {
    @voprf.InvalidElement => "invalid group element"
    @voprf.InvalidScalar => "invalid scalar"
    @voprf.InvalidInput => "invalid input"
    @voprf.InvalidProof => "invalid DLEQ proof"
    @voprf.DeriveKeyPairError => "key pair derivation failed"
    @voprf.InverseError => "modular inverse failed"
    @voprf.ModeMismatch => "VOPRF mode/suite mismatch"
    @voprf.LengthMismatch => "batch length mismatch"
    @voprf.EmptyBatch => "empty batch"
    @voprf.InternalError(m) => m
  }
}

///|
fn u16_be(v : UInt32) -> Bytes {
  Bytes::from_array([((v >> 8) & 0xFFU).to_byte(), (v & 0xFFU).to_byte()])
}

///|
fn read_u16_be(b : Bytes, off : Int32) -> UInt32 {
  (b[off].to_uint() << 8) | b[off + 1].to_uint()
}

///|
fn concat_bytes(parts : Array[Bytes]) -> Bytes {
  let mut total = 0
  for i = 0; i < parts.length(); i = i + 1 {
    total = total + parts[i].length()
  }
  let out = FixedArray::make(total, b'\x00')
  let mut off = 0
  for i = 0; i < parts.length(); i = i + 1 {
    let p = parts[i]
    for j = 0; j < p.length(); j = j + 1 {
      out[off + j] = p[j]
    }
    off = off + p.length()
  }
  Bytes::from_array(out)
}

///|
fn slice_bytes(src : Bytes, off : Int32, len : Int32) -> Bytes {
  let out = FixedArray::make(len, b'\x00')
  for i = 0; i < len; i = i + 1 {
    out[i] = src[off + i]
  }
  Bytes::from_array(out)
}

///|
fn compute_token_key_id(issuer_pk : Bytes) -> Bytes {
  @sha2.sha256(issuer_pk)
}

///|
fn compute_token_input(
  token_type : UInt32,
  nonce : Bytes,
  challenge_digest : Bytes,
  token_key_id : Bytes,
) -> Bytes {
  concat_bytes([u16_be(token_type), nonce, challenge_digest, token_key_id])
}

// ============================================================================
// RFC 9577 / RFC 9578 Wire Structures
// ============================================================================

///|
/// RFC 9577 §2.1 `TokenChallenge` binding issuer, redemption context, and origin.
#derive(Debug, Eq)
pub(all) struct TokenChallenge {
  token_type : UInt32
  issuer_name : Bytes
  redemption_context : Bytes
  origin_info : Bytes
}

///|
/// Creates a validated Type `0x0001` `TokenChallenge`.
/// `redemption_context` must be either empty (`0` bytes) or `32` bytes per RFC 9577.
pub fn TokenChallenge::new(
  issuer_name : Bytes,
  redemption_context : Bytes,
  origin_info : Bytes,
) -> TokenChallenge raise PrivacyPassError {
  if issuer_name.length() == 0 || issuer_name.length() > 65535 {
    raise InvalidChallenge("issuer_name length must be in 1..65535")
  }
  if redemption_context.length() != 0 && redemption_context.length() != 32 {
    raise InvalidChallenge("redemption_context length must be 0 or 32 bytes")
  }
  if origin_info.length() > 65535 {
    raise InvalidChallenge("origin_info length must be <= 65535")
  }
  {
    token_type: TOKEN_TYPE_VOPRF,
    issuer_name,
    redemption_context,
    origin_info,
  }
}

///|
/// Serializes `TokenChallenge` per RFC 9577 §2.1.
pub fn TokenChallenge::encode(
  self : TokenChallenge,
) -> Bytes raise PrivacyPassError {
  if self.token_type != TOKEN_TYPE_VOPRF {
    raise InvalidTokenType(self.token_type)
  }
  if self.issuer_name.length() == 0 || self.issuer_name.length() > 65535 {
    raise InvalidChallenge("invalid issuer_name length")
  }
  if self.redemption_context.length() != 0 &&
    self.redemption_context.length() != 32 {
    raise InvalidChallenge("invalid redemption_context length")
  }
  if self.origin_info.length() > 65535 {
    raise InvalidChallenge("invalid origin_info length")
  }
  concat_bytes([
    u16_be(self.token_type),
    u16_be(self.issuer_name.length().reinterpret_as_uint()),
    self.issuer_name,
    Bytes::from_array([self.redemption_context.length().to_byte()]),
    self.redemption_context,
    u16_be(self.origin_info.length().reinterpret_as_uint()),
    self.origin_info,
  ])
}

///|
/// Computes the 32-byte SHA-256 `challenge_digest = SHA-256(TokenChallenge.encode())`.
pub fn TokenChallenge::context_digest(
  self : TokenChallenge,
) -> Bytes raise PrivacyPassError {
  @sha2.sha256(self.encode())
}

///|
/// RFC 9578 §5.1 `TokenRequest` sent from Client to Issuer.
#derive(Debug, Eq)
pub(all) struct TokenRequest {
  token_type : UInt32
  truncated_token_key_id : Byte
  blinded_msg : Bytes
}

///|
pub fn TokenRequest::encode(self : TokenRequest) -> Bytes {
  concat_bytes([
    u16_be(self.token_type),
    Bytes::from_array([self.truncated_token_key_id]),
    self.blinded_msg,
  ])
}

///|
pub fn TokenRequest::decode(
  suite : @voprf.CipherSuite,
  data : Bytes,
) -> TokenRequest raise PrivacyPassError {
  let expected_len = 3 + suite.element_size()
  if data.length() != expected_len {
    raise InvalidLength(data.length())
  }
  let token_type = read_u16_be(data, 0)
  if token_type != TOKEN_TYPE_VOPRF {
    raise InvalidTokenType(token_type)
  }
  {
    token_type,
    truncated_token_key_id: data[2],
    blinded_msg: slice_bytes(data, 3, suite.element_size()),
  }
}

///|
/// RFC 9578 §5.2 verifiable `TokenResponse` returned by Issuer (evaluated element + DLEQ proof).
#derive(Debug, Eq)
pub(all) struct TokenResponse {
  evaluated_msg : Bytes
  proof : @voprf.Proof
}

///|
pub fn TokenResponse::encode(self : TokenResponse) -> Bytes {
  concat_bytes([self.evaluated_msg, self.proof.to_bytes()])
}

///|
pub fn TokenResponse::decode(
  suite : @voprf.CipherSuite,
  data : Bytes,
) -> TokenResponse raise PrivacyPassError {
  let ne = suite.element_size()
  let np = suite.proof_size()
  if data.length() != ne + np {
    raise InvalidLength(data.length())
  }
  let evaluated_msg = slice_bytes(data, 0, ne)
  let proof = @voprf.Proof::from_bytes(suite, slice_bytes(data, ne, np)) catch {
    _ => raise InvalidProof
  }
  { evaluated_msg, proof, }
}

///|
/// RFC 9578 §2.2 / §5.3 finalized anonymous `Token` presented by Client on redemption.
#derive(Debug, Eq)
pub(all) struct Token {
  token_type : UInt32
  nonce : Bytes
  challenge_digest : Bytes
  token_key_id : Bytes
  authenticator : Bytes
}

///|
pub fn Token::encode(self : Token) -> Bytes {
  concat_bytes([
    u16_be(self.token_type),
    self.nonce,
    self.challenge_digest,
    self.token_key_id,
    self.authenticator,
  ])
}

///|
pub fn Token::decode(
  suite : @voprf.CipherSuite,
  data : Bytes,
) -> Token raise PrivacyPassError {
  let nh = suite.hash_size()
  let expected_len = 2 +
    NONCE_LEN +
    CHALLENGE_DIGEST_LEN +
    TOKEN_KEY_ID_LEN +
    nh
  if data.length() != expected_len {
    raise InvalidLength(data.length())
  }
  let token_type = read_u16_be(data, 0)
  if token_type != TOKEN_TYPE_VOPRF {
    raise InvalidTokenType(token_type)
  }
  {
    token_type,
    nonce: slice_bytes(data, 2, NONCE_LEN),
    challenge_digest: slice_bytes(data, 34, CHALLENGE_DIGEST_LEN),
    token_key_id: slice_bytes(data, 66, TOKEN_KEY_ID_LEN),
    authenticator: slice_bytes(data, 98, nh),
  }
}

// ============================================================================
// Anti-Double-Spend Nonce Registry
// ============================================================================

///|
/// In-memory spent-nonce registry preventing replay / double-spending of
/// redeemed Privacy Pass anonymous tokens.
pub struct NonceRegistry {
  priv spent : Array[Bytes]
}

///|
pub fn NonceRegistry::new() -> NonceRegistry {
  { spent: [], }
}

///|
pub fn NonceRegistry::is_spent(self : NonceRegistry, nonce : Bytes) -> Bool {
  for i = 0; i < self.spent.length(); i = i + 1 {
    if @ct.ct_eq(self.spent[i], nonce) {
      return true
    }
  }
  false
}

///|
/// Marks `nonce` as spent. Returns `true` if newly recorded, or `false` if
/// already present (double-spend).
pub fn NonceRegistry::mark_spent(self : NonceRegistry, nonce : Bytes) -> Bool {
  if self.is_spent(nonce) {
    return false
  }
  self.spent.push(nonce)
  true
}

///|
pub fn NonceRegistry::count(self : NonceRegistry) -> Int32 {
  self.spent.length()
}

// ============================================================================
// Privacy Pass Issuer & Client
// ============================================================================

///|
/// Privacy Pass Type `0x0001` Issuer holding a VOPRF key pair.
pub struct Issuer {
  priv key_pair : @voprf.KeyPair
  priv key_id : Bytes
}

///|
pub fn Issuer::new(
  suite : @voprf.CipherSuite,
  key_pair : @voprf.KeyPair,
) -> Issuer raise PrivacyPassError {
  if key_pair.suite != suite {
    raise VoprfFailed("key pair suite mismatch")
  }
  // Verify sk/pk consistency
  let derived_pk = @voprf.public_key_from_sk(suite, key_pair.sk) catch {
    err => raise VoprfFailed(voprf_err_str(err))
  }
  if !@ct.ct_eq(derived_pk, key_pair.pk) {
    raise VoprfFailed("public key does not match secret key")
  }
  { key_pair, key_id: compute_token_key_id(key_pair.pk), }
}

///|
pub fn Issuer::from_seed(
  suite : @voprf.CipherSuite,
  seed : Bytes,
  key_info : Bytes,
) -> Issuer raise PrivacyPassError {
  let kp = @voprf.derive_key_pair(suite, seed, key_info) catch {
    err => raise VoprfFailed(voprf_err_str(err))
  }
  Issuer::new(suite, kp)
}

///|
pub fn Issuer::suite(self : Issuer) -> @voprf.CipherSuite {
  self.key_pair.suite
}

///|
pub fn Issuer::public_key(self : Issuer) -> Bytes {
  self.key_pair.pk
}

///|
pub fn Issuer::token_key_id(self : Issuer) -> Bytes {
  self.key_id
}

///|
pub fn Issuer::truncated_token_key_id(self : Issuer) -> Byte {
  self.key_id[TOKEN_KEY_ID_LEN - 1]
}

///|
/// Blindly evaluates a single `TokenRequest` and produces a DLEQ-verifiable `TokenResponse`.
pub fn Issuer::issue(
  self : Issuer,
  req : TokenRequest,
  seed : Bytes,
) -> TokenResponse raise PrivacyPassError {
  let (evals, proof) = self.issue_batch([req], seed)
  { evaluated_msg: evals[0], proof, }
}

///|
/// Blindly evaluates a batch of `TokenRequest`s with a single constant-size
/// batched DLEQ zero-knowledge proof.
pub fn Issuer::issue_batch(
  self : Issuer,
  reqs : Array[TokenRequest],
  seed : Bytes,
) -> (Array[Bytes], @voprf.Proof) raise PrivacyPassError {
  if reqs.length() == 0 {
    raise EmptyBatch
  }
  if reqs.length() > 65535 {
    raise InvalidLength(reqs.length())
  }
  let expected_trunc = self.truncated_token_key_id()
  let blinded : Array[Bytes] = Array(capacity=reqs.length())
  for i = 0; i < reqs.length(); i = i + 1 {
    if reqs[i].token_type != TOKEN_TYPE_VOPRF {
      raise InvalidTokenType(reqs[i].token_type)
    }
    if reqs[i].truncated_token_key_id != expected_trunc {
      raise KeyIdMismatch
    }
    blinded.push(reqs[i].blinded_msg)
  }
  @voprf.voprf_blind_evaluate(
    self.key_pair.suite,
    self.key_pair.sk,
    self.key_pair.pk,
    blinded,
    seed,
  ) catch {
    err => raise VoprfFailed(voprf_err_str(err))
  }
}

///|
/// Verifies a presented `Token` against `challenge` and atomically records its
/// `nonce` in `spent_nonces` to prevent double-spend / replay attacks.
///
/// Authenticator verification happens BEFORE marking the nonce spent so forged
/// tokens cannot burn legitimate unused nonces.
pub fn Issuer::verify_and_redeem(
  self : Issuer,
  token : Token,
  challenge : TokenChallenge,
  spent_nonces : NonceRegistry,
) -> Unit raise PrivacyPassError {
  if token.token_type != TOKEN_TYPE_VOPRF {
    raise InvalidTokenType(token.token_type)
  }
  if token.nonce.length() != NONCE_LEN {
    raise InvalidLength(token.nonce.length())
  }
  if token.challenge_digest.length() != CHALLENGE_DIGEST_LEN {
    raise InvalidLength(token.challenge_digest.length())
  }
  if token.token_key_id.length() != TOKEN_KEY_ID_LEN {
    raise InvalidLength(token.token_key_id.length())
  }
  if !@ct.ct_eq(token.token_key_id, self.key_id) {
    raise KeyIdMismatch
  }
  let expected_digest = challenge.context_digest()
  if !@ct.ct_eq(token.challenge_digest, expected_digest) {
    raise ChallengeMismatch
  }
  let token_input = compute_token_input(
    token.token_type,
    token.nonce,
    token.challenge_digest,
    token.token_key_id,
  )
  let expected_auth = @voprf.voprf_full_evaluate(
    self.key_pair.suite,
    self.key_pair.sk,
    token_input,
  ) catch {
    err => raise VoprfFailed(voprf_err_str(err))
  }
  if !@ct.ct_eq(token.authenticator, expected_auth) {
    raise InvalidAuthenticator
  }
  if !spent_nonces.mark_spent(token.nonce) {
    raise DoubleSpend
  }
}

///|
/// Client-side state held between `create_request` and `finalize_token`.
#derive(Debug, Eq)
pub struct ClientRequestState {
  priv suite : @voprf.CipherSuite
  priv token_type : UInt32
  priv nonce : Bytes
  priv challenge_digest : Bytes
  priv token_key_id : Bytes
  priv blind_state : @voprf.BlindState
}

///|
/// Privacy Pass Type `0x0001` Client.
pub struct Client {
  priv suite : @voprf.CipherSuite
  priv issuer_pk : Bytes
  priv key_id : Bytes
}

///|
pub fn Client::new(
  suite : @voprf.CipherSuite,
  issuer_pk : Bytes,
) -> Client raise PrivacyPassError {
  if issuer_pk.length() != suite.element_size() {
    raise InvalidLength(issuer_pk.length())
  }
  @voprf.validate_public_key(suite, issuer_pk) catch {
    err => raise VoprfFailed(voprf_err_str(err))
  }
  { suite, issuer_pk, key_id: compute_token_key_id(issuer_pk), }
}

///|
/// Blinds a fresh 32-byte `nonce` + `challenge` into a `TokenRequest` and local
/// `ClientRequestState`.
pub fn Client::create_request(
  self : Client,
  challenge : TokenChallenge,
  nonce : Bytes,
  blind_seed : Bytes,
) -> (TokenRequest, ClientRequestState) raise PrivacyPassError {
  if nonce.length() != NONCE_LEN {
    raise InvalidLength(nonce.length())
  }
  let challenge_digest = challenge.context_digest()
  let token_input = compute_token_input(
    TOKEN_TYPE_VOPRF,
    nonce,
    challenge_digest,
    self.key_id,
  )
  let blind_state = @voprf.voprf_blind(self.suite, token_input, blind_seed) catch {
    err => raise VoprfFailed(voprf_err_str(err))
  }
  let req : TokenRequest = {
    token_type: TOKEN_TYPE_VOPRF,
    truncated_token_key_id: self.key_id[TOKEN_KEY_ID_LEN - 1],
    blinded_msg: blind_state.blinded_element,
  }
  let state : ClientRequestState = {
    suite: self.suite,
    token_type: TOKEN_TYPE_VOPRF,
    nonce,
    challenge_digest,
    token_key_id: self.key_id,
    blind_state,
  }
  (req, state)
}

///|
/// Verifies the Issuer's DLEQ proof, unblinds the evaluation, and produces a
/// ready-to-redeem anonymous `Token`.
pub fn Client::finalize_token(
  self : Client,
  state : ClientRequestState,
  resp : TokenResponse,
  issuer_pk : Bytes,
) -> Token raise PrivacyPassError {
  let tokens = self.finalize_batch(
    [state],
    [resp.evaluated_msg],
    resp.proof,
    issuer_pk,
  )
  tokens[0]
}

///|
/// Verifies a batched Issuer DLEQ proof and unblinds all tokens in one pass.
pub fn Client::finalize_batch(
  self : Client,
  states : Array[ClientRequestState],
  evaluated_msgs : Array[Bytes],
  proof : @voprf.Proof,
  issuer_pk : Bytes,
) -> Array[Token] raise PrivacyPassError {
  if states.length() == 0 {
    raise EmptyBatch
  }
  if states.length() > 65535 {
    raise InvalidLength(states.length())
  }
  if states.length() != evaluated_msgs.length() {
    raise InvalidLength(evaluated_msgs.length())
  }
  if !@ct.ct_eq(issuer_pk, self.issuer_pk) {
    raise KeyIdMismatch
  }
  let blind_states : Array[@voprf.BlindState] = Array(capacity=states.length())
  for i = 0; i < states.length(); i = i + 1 {
    if states[i].token_type != TOKEN_TYPE_VOPRF {
      raise InvalidTokenType(states[i].token_type)
    }
    if states[i].suite != self.suite {
      raise VoprfFailed("client request state suite mismatch")
    }
    if !@ct.ct_eq(states[i].token_key_id, self.key_id) {
      raise KeyIdMismatch
    }
    blind_states.push(states[i].blind_state)
  }
  let authenticators = @voprf.voprf_finalize_batch(
    blind_states, issuer_pk, evaluated_msgs, proof,
  ) catch {
    @voprf.InvalidProof => raise InvalidProof
    err => raise VoprfFailed(voprf_err_str(err))
  }
  let tokens : Array[Token] = Array(capacity=states.length())
  for i = 0; i < states.length(); i = i + 1 {
    tokens.push({
      token_type: states[i].token_type,
      nonce: states[i].nonce,
      challenge_digest: states[i].challenge_digest,
      token_key_id: states[i].token_key_id,
      authenticator: authenticators[i],
    })
  }
  tokens
}