///|
priv struct ActionExecution {
  surface_id : String
  component_id : String
  timestamp : String
  metadata : Json?
  component : Json
  context : EvaluationContext
}

///|
/// Activates a declared action and resumes it when dependent RPC results arrive.
pub fn Runtime::activate(
  self : Runtime,
  surface_id : String,
  component_id : String,
  timestamp : String,
  metadata? : Json,
  scope~ : String = "/",
  index? : Int32,
) -> RendererMessage? raise ProtocolError {
  guard self.store.surfaces.get(surface_id) is Some(surface) &&
    surface.components.get(component_id) is Some(component) else {
    raise StateError("unknown action component")
  }
  let (catalog, _) = self.catalogs.component_definition(
    component,
    surface.catalog_id,
  )
  self.next_call += 1
  let context = {
    surface_id: Some(surface_id),
    catalog_id: catalog.id,
    scope,
    index,
    caller: Renderer,
    user_activation: true,
    imperative: true,
    allow_remote: true,
    operation_id: Some("action-" + self.next_call.to_string()),
  }
  self.run_action({
    surface_id,
    component_id,
    timestamp,
    metadata: metadata.map(copy_json),
    component: copy_json(component),
    context,
  })
}

///|
fn Runtime::finish_action(self : Runtime, execution : ActionExecution) -> Unit {
  let ids = self.calls
    .iter()
    .filter_map(entry => {
      if entry.1.operation_id == execution.context.operation_id {
        Some(entry.0)
      } else {
        None
      }
    })
    .collect()
  for id in ids {
    ignore(self.take_response(id))
  }
}

///|
fn Runtime::run_action(
  self : Runtime,
  execution : ActionExecution,
) -> RendererMessage? raise ProtocolError {
  try {
    let message = self.action_result(execution)
    self.finish_action(execution)
    message
  } catch {
    RuntimeError(code="PENDING", reason=id) => {
      match self.continuations.get(id) {
        Some(waiting) => waiting.push(execution)
        None => self.continuations[id] = [execution]
      }
      self.outgoing.pop()
    }
    CallFailed(id~, message~, ..) => {
      self.finish_action(execution)
      Some(
        Error(
          RendererError::new("EXPRESSION_ERROR", message, function_call_id=id),
        ),
      )
    }
    error => {
      self.finish_action(execution)
      raise error
    }
  }
}

///|
fn Runtime::action_result(
  self : Runtime,
  execution : ActionExecution,
) -> RendererMessage? raise ProtocolError {
  let { surface_id, component_id, timestamp, metadata, component, context, } = execution
  if component is { "@checks": Array(rules), .. } {
    let results = self.check(rules, {
      ..context,
      user_activation: false,
      imperative: false,
      operation_id: None,
    })
    if results.iter().any(result => !coerce_boolean(result)) {
      return None
    }
  }
  guard component is { "action": action, .. } else {
    raise StateError("component has no action")
  }
  match action {
    { "event": Object(event), .. } => {
      let body : Map[String, Json] = {
        "name": Json::string(string_field(event, "name", "/action/event")),
        "surfaceId": Json::string(surface_id),
        "sourceComponentId": Json::string(component_id),
        "timestamp": Json::string(timestamp),
        "context": self.evaluate(
          event.get("context").unwrap_or(Json::empty_object()),
          context,
        ),
      }
      if event.get("userMessage") is Some(message) {
        body["userMessage"] = self.evaluate(message, context)
      }
      if metadata is Some(value) {
        body["metadata"] = copy_json(value)
      }
      Some(
        UserAction(
          Action::from_json({ "version": "1.0", "action": Json::object(body) }),
        ),
      )
    }
    { "functionCall": call, .. } => {
      ignore(self.evaluate(call, context))
      None
    }
    _ => raise Invalid(path="/action", reason="invalid action definition")
  }
}

///|
pub fn Runtime::renderer_data_model(
  self : Runtime,
  surface_id : String,
) -> Json? raise ProtocolError {
  self.store.renderer_data_model(surface_id)
}