///|
/// IETF RFC 9497 Core Types, Ciphersuites, Modes, Errors, and Unified Prime-Order
/// Group Abstraction over Ristretto255-SHA512 and P256-SHA256.

///|
#derive(Debug, Eq)
pub(all) enum CipherSuite {
  Ristretto255Sha512
  P256Sha256
}

///|
/// Returns the exact RFC 9497 §4 ASCII ciphersuite identifier string.
pub fn CipherSuite::identifier(self : CipherSuite) -> Bytes {
  match self {
    Ristretto255Sha512 => b"ristretto255-SHA512"
    P256Sha256 => b"P256-SHA256"
  }
}

///|
/// Serialized group element length `Ne` in bytes (32 for Ristretto255, 33 for P-256).
pub fn CipherSuite::element_size(self : CipherSuite) -> Int32 {
  match self {
    Ristretto255Sha512 => 32
    P256Sha256 => 33
  }
}

///|
/// Serialized scalar length `Ns` in bytes (32 for both suites).
pub fn CipherSuite::scalar_size(self : CipherSuite) -> Int32 {
  match self {
    Ristretto255Sha512 => 32
    P256Sha256 => 32
  }
}

///|
/// Hash output length `Nh` in bytes (64 for SHA-512, 32 for SHA-256).
pub fn CipherSuite::hash_size(self : CipherSuite) -> Int32 {
  match self {
    Ristretto255Sha512 => 64
    P256Sha256 => 32
  }
}

///|
/// Serialized DLEQ proof length `2 * Ns` in bytes (64 for both suites).
pub fn CipherSuite::proof_size(self : CipherSuite) -> Int32 {
  self.scalar_size() * 2
}

///|
#derive(Debug, Eq)
pub(all) enum Mode {
  Oprf
  Voprf
  Poprf
}

///|
/// Returns the RFC 9497 §3.1 1-byte protocol mode identifier (`0x00`/`0x01`/`0x02`).
pub fn Mode::to_byte(self : Mode) -> Byte {
  match self {
    Oprf => b'\x00'
    Voprf => b'\x01'
    Poprf => b'\x02'
  }
}

///|
#derive(Debug, Eq)
pub suberror VoprfError {
  InvalidElement
  InvalidScalar
  InvalidInput
  InvalidProof
  DeriveKeyPairError
  InverseError
  ModeMismatch
  LengthMismatch
  EmptyBatch
  InternalError(String)
}

///|
/// Server key pair `(sk, pk)` bound to a specific `CipherSuite`.
#derive(Debug, Eq)
pub(all) struct KeyPair {
  sk : Bytes
  pk : Bytes
  suite : CipherSuite
}

///|
/// Client blinding state retained between `Blind` and `Finalize`.
#derive(Debug, Eq)
pub(all) struct BlindState {
  suite : CipherSuite
  mode : Mode
  blind : Bytes
  input : Bytes
  blinded_element : Bytes
}

///|
/// RFC 9497 §2.2 DLEQ zero-knowledge proof `(c, s)` serialized as canonical scalars.
#derive(Debug, Eq)
pub(all) struct Proof {
  c : Bytes
  s : Bytes
}

///|
/// Serializes a DLEQ proof as `c || s` (`2 * Ns` bytes).
pub fn Proof::to_bytes(self : Proof) -> Bytes {
  let out = FixedArray::make(self.c.length() + self.s.length(), b'\x00')
  for i = 0; i < self.c.length(); i = i + 1 {
    out[i] = self.c[i]
  }
  for i = 0; i < self.s.length(); i = i + 1 {
    out[self.c.length() + i] = self.s[i]
  }
  Bytes::from_array(out)
}

///|
/// Strictly deserializes a `Proof` (`c || s`) for `suite`, validating that both
/// `c` and `s` are canonical scalars for `suite`.
pub fn Proof::from_bytes(
  suite : CipherSuite,
  data : Bytes,
) -> Proof raise VoprfError {
  let ns = suite.scalar_size()
  if data.length() != ns * 2 {
    raise InvalidProof
  }
  let c_arr = FixedArray::make(ns, b'\x00')
  let s_arr = FixedArray::make(ns, b'\x00')
  for i = 0; i < ns; i = i + 1 {
    c_arr[i] = data[i]
    s_arr[i] = data[ns + i]
  }
  let c = Bytes::from_array(c_arr)
  let s = Bytes::from_array(s_arr)
  ignore(deserialize_scalar(suite, c) catch { _ => raise InvalidProof })
  ignore(deserialize_scalar(suite, s) catch { _ => raise InvalidProof })
  { c, s, }
}

// ============================================================================
// Internal RFC 9497 Helpers & Unified Group Dispatch
// ============================================================================

///|
fn i2osp2(v : Int32) -> Bytes raise VoprfError {
  if v < 0 || v > 65535 {
    raise InvalidInput
  }
  Bytes::from_array([((v >> 8) & 0xFF).to_byte(), (v & 0xFF).to_byte()])
}

///|
fn concat_parts(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)
}

///|
/// RFC 9497 §3.1 `CreateContextString(mode, identifier)`:
/// `"OPRFV1-" || I2OSP(mode, 1) || "-" || identifier`.
fn create_context_string(mode : Mode, suite : CipherSuite) -> Bytes {
  concat_parts([
    b"OPRFV1-",
    Bytes::from_array([mode.to_byte()]),
    b"-",
    suite.identifier(),
  ])
}

///|
fn suite_hash(suite : CipherSuite, parts : Array[BytesView]) -> Bytes {
  match suite {
    Ristretto255Sha512 => @sha2.sha512_parts(parts)
    P256Sha256 => @sha2.sha256_parts(parts)
  }
}

///|
priv enum GroupScalar {
  R255(@r255.Scalar)
  P256(@p256.Scalar)
}

///|
priv enum GroupElem {
  R255(@r255.Point)
  P256(@p256.Point)
}

///|
fn elem_identity(suite : CipherSuite) -> GroupElem {
  match suite {
    Ristretto255Sha512 => R255(@r255.Point::identity())
    P256Sha256 => P256(@p256.Point::identity())
  }
}

///|
fn elem_generator(suite : CipherSuite) -> GroupElem {
  match suite {
    Ristretto255Sha512 => R255(@r255.Point::generator())
    P256Sha256 => P256(@p256.Point::generator())
  }
}

///|
fn elem_is_identity(e : GroupElem) -> Bool {
  match e {
    R255(p) => p.is_identity()
    P256(p) => p.is_identity()
  }
}

///|
fn elem_equals(a : GroupElem, b : GroupElem) -> Bool {
  match (a, b) {
    (R255(p), R255(q)) => p.equals(q)
    (P256(p), P256(q)) => p.equals(q)
    _ => false
  }
}

///|
fn elem_add(a : GroupElem, b : GroupElem) -> GroupElem raise VoprfError {
  match (a, b) {
    (R255(p), R255(q)) => R255(p.add(q))
    (P256(p), P256(q)) => P256(p.add(q))
    _ => raise InternalError("suite mismatch in elem_add")
  }
}

///|
fn elem_mul(e : GroupElem, s : GroupScalar) -> GroupElem raise VoprfError {
  match (e, s) {
    (R255(p), R255(k)) => R255(p.mul(k))
    (P256(p), P256(k)) => P256(p.mul(k))
    _ => raise InternalError("suite mismatch in elem_mul")
  }
}

///|
fn elem_mul_base(s : GroupScalar) -> GroupElem {
  match s {
    R255(k) => R255(@r255.Point::mul_base(k))
    P256(k) => P256(@p256.Point::mul_base(k))
  }
}

///|
fn serialize_element(e : GroupElem) -> Bytes raise VoprfError {
  match e {
    R255(p) => p.encode()
    P256(p) =>
      p.encode_compressed() catch {
        @p256.IdentityElement => raise InvalidElement
        _ => raise InvalidElement
      }
  }
}

///|
/// RFC 9497 §2.1 & §4 `DeserializeElement`: strictly decodes canonical encoding
/// AND rejects the group identity element.
fn deserialize_element(
  suite : CipherSuite,
  buf : Bytes,
) -> GroupElem raise VoprfError {
  match suite {
    Ristretto255Sha512 => {
      let pt = @r255.Point::decode(buf) catch { _ => raise InvalidElement }
      if pt.is_identity() {
        raise InvalidElement
      }
      R255(pt)
    }
    P256Sha256 => {
      let pt = @p256.Point::decode_compressed(buf) catch {
        _ => raise InvalidElement
      }
      if pt.is_identity() {
        raise InvalidElement
      }
      P256(pt)
    }
  }
}

///|
fn scalar_is_zero(s : GroupScalar) -> Bool {
  match s {
    R255(k) => k.is_zero()
    P256(k) => k.is_zero()
  }
}

///|
fn scalar_add(a : GroupScalar, b : GroupScalar) -> GroupScalar raise VoprfError {
  match (a, b) {
    (R255(x), R255(y)) => R255(x.add(y))
    (P256(x), P256(y)) => P256(x.add(y))
    _ => raise InternalError("suite mismatch in scalar_add")
  }
}

///|
fn scalar_sub(a : GroupScalar, b : GroupScalar) -> GroupScalar raise VoprfError {
  match (a, b) {
    (R255(x), R255(y)) => R255(x.sub(y))
    (P256(x), P256(y)) => P256(x.sub(y))
    _ => raise InternalError("suite mismatch in scalar_sub")
  }
}

///|
fn scalar_mul(a : GroupScalar, b : GroupScalar) -> GroupScalar raise VoprfError {
  match (a, b) {
    (R255(x), R255(y)) => R255(x.mul(y))
    (P256(x), P256(y)) => P256(x.mul(y))
    _ => raise InternalError("suite mismatch in scalar_mul")
  }
}

///|
fn scalar_invert(s : GroupScalar) -> GroupScalar raise VoprfError {
  match s {
    R255(k) => R255(k.invert()) catch { _ => raise InverseError }
    P256(k) => P256(k.invert()) catch { _ => raise InverseError }
  }
}

///|
fn serialize_scalar(s : GroupScalar) -> Bytes {
  match s {
    R255(k) => k.to_bytes()
    P256(k) => k.to_bytes()
  }
}

///|
fn deserialize_scalar(
  suite : CipherSuite,
  buf : Bytes,
) -> GroupScalar raise VoprfError {
  match suite {
    Ristretto255Sha512 =>
      R255(@r255.Scalar::from_bytes_canonical(buf)) catch {
        _ => raise InvalidScalar
      }
    P256Sha256 =>
      P256(@p256.Scalar::from_bytes_canonical(buf)) catch {
        _ => raise InvalidScalar
      }
  }
}

///|
fn deserialize_nonzero_scalar(
  suite : CipherSuite,
  buf : Bytes,
) -> GroupScalar raise VoprfError {
  let s = deserialize_scalar(suite, buf)
  if scalar_is_zero(s) {
    raise InvalidScalar
  }
  s
}

///|
fn hash_to_group(
  suite : CipherSuite,
  mode : Mode,
  msg : Bytes,
) -> GroupElem raise VoprfError {
  let dst = concat_parts([b"HashToGroup-", create_context_string(mode, suite)])
  match suite {
    Ristretto255Sha512 =>
      R255(@r255.Point::hash_to_group(msg, dst)) catch {
        _ => raise InvalidInput
      }
    P256Sha256 =>
      P256(@p256.Point::hash_to_group(msg, dst)) catch {
        _ => raise InvalidInput
      }
  }
}

///|
fn hash_to_scalar_with_dst(
  suite : CipherSuite,
  msg : Bytes,
  dst : Bytes,
) -> GroupScalar raise VoprfError {
  match suite {
    Ristretto255Sha512 =>
      R255(@r255.Scalar::hash_to_scalar(msg, dst)) catch {
        _ => raise InternalError("ristretto255 hash_to_scalar failed")
      }
    P256Sha256 =>
      P256(@p256.Scalar::hash_to_scalar(msg, dst)) catch {
        _ => raise InternalError("p256 hash_to_scalar failed")
      }
  }
}

///|
fn hash_to_scalar(
  suite : CipherSuite,
  mode : Mode,
  msg : Bytes,
) -> GroupScalar raise VoprfError {
  let dst = concat_parts([b"HashToScalar-", create_context_string(mode, suite)])
  hash_to_scalar_with_dst(suite, msg, dst)
}

///|
/// Deterministically derives a non-zero scalar from `seed` under a domain-separated DST.
fn derive_nonzero_scalar(
  suite : CipherSuite,
  seed : Bytes,
  dst : Bytes,
) -> GroupScalar raise VoprfError {
  for counter = 0; counter <= 255; counter = counter + 1 {
    let input = concat_parts([seed, Bytes::from_array([counter.to_byte()])])
    let s = hash_to_scalar_with_dst(suite, input, dst)
    if !scalar_is_zero(s) {
      return s
    }
  }
  raise DeriveKeyPairError
}