///|
/// Opaque error raised by `RequestStateCodec::verify` (never leaks decoded payload or binding values).
#derive(Debug, Eq)
#non_exhaustive
pub(all) suberror RequestStateError {
  InvalidKeyLength(Int32)
  Malformed
  InvalidMac
  Expired
  BindMismatch
}

///|
/// Opt-in HMAC-SHA256 integrity codec for MCP 2026-07-28 multi-round-trip `requestState`
/// (exact wire format parity with `@modelcontextprotocol/server` `createRequestStateCodec`):
///
///     "v1." b64url({"p":,"exp":,"b":?}) "." b64url(mac)
///
/// where `bindTag = b64url(HMAC-SHA256(key, "mcp.requestState.bind:" + bind_value)[:16])`.
/// Signed, not encrypted; verification is fail-closed and constant-time.
pub struct RequestStateCodec {
  priv key : Bytes
  priv ttl_seconds : Int64
  priv has_bind : Bool
}

///|
let request_state_prefix : String = "v1."

///|
let request_state_bind_label : String = "mcp.requestState.bind:"

///|
/// Creates a `RequestStateCodec`. `key` MUST be at least 32 bytes (256 bits).
pub fn RequestStateCodec::RequestStateCodec(
  key~ : Bytes,
  ttl_seconds~ : Int64 = 600L,
  has_bind~ : Bool = false,
) -> RequestStateCodec raise RequestStateError {
  if key.length() < 32 {
    raise RequestStateError::InvalidKeyLength(key.length())
  }
  { key, ttl_seconds, has_bind, }
}

///|
/// Convenience constructor accepting a UTF-8 string secret (must be >= 32 UTF-8 bytes).
pub fn RequestStateCodec::from_secret(
  secret~ : String,
  ttl_seconds~ : Int64 = 600L,
  has_bind~ : Bool = false,
) -> RequestStateCodec raise RequestStateError {
  RequestStateCodec::RequestStateCodec(
    key=@utf8.encode(secret),
    ttl_seconds~,
    has_bind~,
  )
}

///|
fn RequestStateCodec::compute_bind_tag(
  self : RequestStateCodec,
  bind_value : String,
) -> String {
  let msg = @utf8.encode("\{request_state_bind_label}\{bind_value}")
  let mac = @crypto.hmac_sha256(key=self.key[:], data=msg[:])
  @crypto.base64url_encode(mac[:16])
}

///|
/// Seals `payload` into a versioned HMAC-SHA256-authenticated `requestState` string.
/// `now_seconds` is the current Unix timestamp in seconds; `bind_value` must be provided
/// when the codec was created with `has_bind=true`.
pub fn RequestStateCodec::mint(
  self : RequestStateCodec,
  payload : Json,
  now_seconds~ : Int64,
  bind_value? : String,
) -> String raise RequestStateError {
  let env : Map[String, Json] = Map([
    ("p", payload),
    ("exp", Json::number((now_seconds + self.ttl_seconds).to_double())),
  ])
  if self.has_bind {
    match bind_value {
      Some(bv) => env["b"] = Json::string(self.compute_bind_tag(bv))
      None => raise RequestStateError::BindMismatch
    }
  }
  let body = @crypto.base64url_encode(
    @utf8.encode(Json::object(env).stringify())[:],
  )
  let mac_input = @utf8.encode("\{request_state_prefix}\{body}")
  let mac = @crypto.hmac_sha256(key=self.key[:], data=mac_input[:])
  "\{request_state_prefix}\{body}.\{@crypto.base64url_encode(mac[:])}"
}

///|
/// Verifies an echoed `requestState` string (fail-closed, constant-time MAC & bind-tag check)
/// and returns the original JSON payload.
pub fn RequestStateCodec::verify(
  self : RequestStateCodec,
  state : String,
  now_seconds~ : Int64,
  bind_value? : String,
) -> Json raise RequestStateError {
  if !state.has_prefix(request_state_prefix) {
    raise RequestStateError::Malformed
  }
  let rest = state[request_state_prefix.length():].to_owned()
  let dot_idx = match rest.rev_find(".") {
    Some(i) if i > 0 => i
    _ => raise RequestStateError::Malformed
  }
  let body = rest[:dot_idx].to_owned()
  let mac_b64 = rest[dot_idx + 1:].to_owned()
  let mac_bytes = @crypto.base64url_decode(mac_b64) catch {
    _ => raise RequestStateError::Malformed
  }
  let expected_mac = @crypto.hmac_sha256(
    key=self.key[:],
    data=@utf8.encode("\{request_state_prefix}\{body}")[:],
  )
  if !@crypto.constant_time_equal(mac_bytes[:], expected_mac[:]) {
    raise RequestStateError::InvalidMac
  }
  let body_bytes = @crypto.base64url_decode(body) catch {
    _ => raise RequestStateError::Malformed
  }
  let body_str = @utf8.decode(body_bytes) catch {
    _ => raise RequestStateError::Malformed
  }
  let parsed = @json.parse(body_str) catch {
    _ => raise RequestStateError::Malformed
  }
  let obj = match parsed {
    Object(m) => m
    _ => raise RequestStateError::Malformed
  }
  let exp = match obj.get("exp") {
    Some(Number(n, ..)) => n.to_int64()
    _ => raise RequestStateError::Malformed
  }
  if exp < now_seconds {
    raise RequestStateError::Expired
  }
  if self.has_bind {
    let bv = match bind_value {
      Some(v) => v
      None => raise RequestStateError::BindMismatch
    }
    let expected_tag = self.compute_bind_tag(bv)
    match obj.get("b") {
      Some(String(actual_tag)) =>
        if !@crypto.constant_time_equal(
            @utf8.encode(actual_tag)[:],
            @utf8.encode(expected_tag)[:],
          ) {
          raise RequestStateError::BindMismatch
        }
      _ => raise RequestStateError::BindMismatch
    }
  } else if obj.contains("b") {
    // Fail-closed on configuration drift: bound token rejected by unbound codec
    raise RequestStateError::BindMismatch
  }
  match obj.get("p") {
    Some(p) => p
    None => Json::null()
  }
}