///|
/// MCP 2026-07-28 SEP-1865 `subscriptions/listen` filter and event-bus helpers.
#derive(Debug, Eq)
pub(all) struct SubscriptionFilter {
  tools_list_changed : Bool
  prompts_list_changed : Bool
  resources_list_changed : Bool
  resource_subscriptions : Array[String]
}

///|
pub fn SubscriptionFilter::SubscriptionFilter(
  tools_list_changed~ : Bool = false,
  prompts_list_changed~ : Bool = false,
  resources_list_changed~ : Bool = false,
  resource_subscriptions~ : Array[String] = [],
) -> SubscriptionFilter {
  {
    tools_list_changed,
    prompts_list_changed,
    resources_list_changed,
    resource_subscriptions,
  }
}

///|
pub fn SubscriptionFilter::is_empty(self : SubscriptionFilter) -> Bool {
  !self.tools_list_changed &&
  !self.prompts_list_changed &&
  !self.resources_list_changed &&
  self.resource_subscriptions.is_empty()
}

///|
pub fn SubscriptionFilter::to_json(self : SubscriptionFilter) -> Json {
  let m : Map[String, Json] = Map([])
  if self.tools_list_changed {
    m["toolsListChanged"] = Json::boolean(true)
  }
  if self.prompts_list_changed {
    m["promptsListChanged"] = Json::boolean(true)
  }
  if self.resources_list_changed {
    m["resourcesListChanged"] = Json::boolean(true)
  }
  if !self.resource_subscriptions.is_empty() {
    m["resourceSubscriptions"] = Json::array(
      self.resource_subscriptions.map(u => Json::string(u)),
    )
  }
  Json::object(m)
}

///|
/// Change event published onto `McpServer`'s internal event bus for
/// `subscriptions/listen` delivery (SEP-1865).
#derive(Debug, Eq)
#non_exhaustive
pub(all) enum ServerEvent {
  ToolsListChanged
  PromptsListChanged
  ResourcesListChanged
  ResourceUpdated(String)
}

///|
/// Parses `params.notifications` from a `subscriptions/listen` request.
pub fn parse_subscription_filter(
  params_opt : Map[String, Json]?,
) -> SubscriptionFilter raise McpProtocolError {
  let params = match params_opt {
    Some(p) => p
    None =>
      raise McpProtocolError::invalid_params(
        "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter",
      )
  }
  let notif_obj = match params.get("notifications") {
    Some(Object(m)) => m
    _ =>
      raise McpProtocolError::invalid_params(
        "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter",
      )
  }
  let tools_list_changed = match notif_obj.get("toolsListChanged") {
    None => false
    Some(True) => true
    Some(False) => false
    Some(_) =>
      raise McpProtocolError::invalid_params(
        "Invalid params: notifications.toolsListChanged must be a boolean",
      )
  }
  let prompts_list_changed = match notif_obj.get("promptsListChanged") {
    None => false
    Some(True) => true
    Some(False) => false
    Some(_) =>
      raise McpProtocolError::invalid_params(
        "Invalid params: notifications.promptsListChanged must be a boolean",
      )
  }
  let resources_list_changed = match notif_obj.get("resourcesListChanged") {
    None => false
    Some(True) => true
    Some(False) => false
    Some(_) =>
      raise McpProtocolError::invalid_params(
        "Invalid params: notifications.resourcesListChanged must be a boolean",
      )
  }
  let resource_subscriptions : Array[String] = []
  match notif_obj.get("resourceSubscriptions") {
    None => ()
    Some(Array(items)) =>
      for item in items {
        match item {
          String(u) => resource_subscriptions.push(u)
          _ =>
            raise McpProtocolError::invalid_params(
              "Invalid params: notifications.resourceSubscriptions entries must be strings",
            )
        }
      }
    Some(_) =>
      raise McpProtocolError::invalid_params(
        "Invalid params: notifications.resourceSubscriptions must be an array of strings",
      )
  }
  {
    tools_list_changed,
    prompts_list_changed,
    resources_list_changed,
    resource_subscriptions,
  }
}

///|
/// Narrows a requested `SubscriptionFilter` against the server's advertised `capabilities`.
pub fn honored_subscription_filter(
  requested : SubscriptionFilter,
  capabilities : Json,
) -> SubscriptionFilter {
  let caps = match capabilities {
    Object(m) => m
    _ => Map([])
  }
  let allow_tools = match caps.get("tools") {
    Some(Object(tm)) => tm.get("listChanged") == Some(Json::boolean(true))
    _ => false
  }
  let allow_prompts = match caps.get("prompts") {
    Some(Object(pm)) => pm.get("listChanged") == Some(Json::boolean(true))
    _ => false
  }
  let allow_resources_list = match caps.get("resources") {
    Some(Object(rm)) => rm.get("listChanged") == Some(Json::boolean(true))
    _ => false
  }
  let allow_resources_sub = match caps.get("resources") {
    Some(Object(rm)) => rm.get("subscribe") == Some(Json::boolean(true))
    _ => false
  }
  {
    tools_list_changed: requested.tools_list_changed && allow_tools,
    prompts_list_changed: requested.prompts_list_changed && allow_prompts,
    resources_list_changed: requested.resources_list_changed &&
    allow_resources_list,
    resource_subscriptions: if allow_resources_sub {
      requested.resource_subscriptions.copy()
    } else {
      []
    },
  }
}

///|
/// Returns true if `filter` opted in to `event`.
pub fn subscription_filter_accepts(
  filter : SubscriptionFilter,
  event : ServerEvent,
) -> Bool {
  match event {
    ToolsListChanged => filter.tools_list_changed
    PromptsListChanged => filter.prompts_list_changed
    ResourcesListChanged => filter.resources_list_changed
    ResourceUpdated(uri) => filter.resource_subscriptions.contains(uri)
  }
}

///|
/// Builds the leading `notifications/subscriptions/acknowledged` notification stamped with `subscriptionId`.
pub fn make_subscription_ack(
  subscription_id : Json,
  honored : SubscriptionFilter,
) -> Json {
  Json::object(
    Map([
      ("jsonrpc", Json::string("2.0")),
      ("method", Json::string("notifications/subscriptions/acknowledged")),
      (
        "params",
        Json::object(
          Map([
            ("notifications", honored.to_json()),
            (
              "_meta",
              Json::object(Map([(meta_key_subscription_id, subscription_id)])),
            ),
          ]),
        ),
      ),
    ]),
  )
}

///|
/// Builds a subscription-stamped change notification for `event`.
pub fn make_subscription_event_notification(
  subscription_id : Json,
  event : ServerEvent,
) -> Json {
  let meta = Json::object(Map([(meta_key_subscription_id, subscription_id)]))
  match event {
    ToolsListChanged =>
      Json::object(
        Map([
          ("jsonrpc", Json::string("2.0")),
          ("method", Json::string("notifications/tools/list_changed")),
          ("params", Json::object(Map([("_meta", meta)]))),
        ]),
      )
    PromptsListChanged =>
      Json::object(
        Map([
          ("jsonrpc", Json::string("2.0")),
          ("method", Json::string("notifications/prompts/list_changed")),
          ("params", Json::object(Map([("_meta", meta)]))),
        ]),
      )
    ResourcesListChanged =>
      Json::object(
        Map([
          ("jsonrpc", Json::string("2.0")),
          ("method", Json::string("notifications/resources/list_changed")),
          ("params", Json::object(Map([("_meta", meta)]))),
        ]),
      )
    ResourceUpdated(uri) =>
      Json::object(
        Map([
          ("jsonrpc", Json::string("2.0")),
          ("method", Json::string("notifications/resources/updated")),
          (
            "params",
            Json::object(Map([("uri", Json::string(uri)), ("_meta", meta)])),
          ),
        ]),
      )
  }
}

///|
/// Builds the graceful-close `SubscriptionsListenResult` response frame.
pub fn make_subscription_close_result(
  subscription_id : Json,
  server_info : McpImplementation,
) -> Json {
  Json::object(
    Map([
      ("jsonrpc", Json::string("2.0")),
      ("id", subscription_id),
      (
        "result",
        Json::object(
          Map([
            ("resultType", Json::string("complete")),
            (
              "_meta",
              Json::object(
                Map([
                  (meta_key_subscription_id, subscription_id),
                  (meta_key_server_info, server_info.to_json()),
                ]),
              ),
            ),
          ]),
        ),
      ),
    ]),
  )
}