///|
/// A renderer action with resolved context. Transport metadata is supplied
/// separately by the transport and is not inserted into this envelope.
pub struct Action {
  priv wire : Json
  name : String
  surface_id : String
  source_component_id : String
  timestamp : String
}

///|
pub fn Action::from_json(value : Json) -> Action raise ProtocolError {
  check_schema(schemas().renderer, value)
  decode_action(value)
}

///|
fn decode_action(value : Json) -> Action raise ProtocolError {
  let envelope = object(value, "")
  guard envelope.length() == 2 &&
    envelope.get("version") == Some(Json::string("1.0")) &&
    envelope.contains("action") else {
    raise Invalid(path="", reason="expected A2UI 1.0 action envelope")
  }
  let body = object(envelope["action"], "/action")
  guard @schema.format_valid(
    "date-time",
    string_field(body, "timestamp", "/action"),
  ) else {
    raise Invalid(
      path="/action/timestamp",
      reason="expected ISO 8601 date-time",
    )
  }
  ignore(object(body.get("context").unwrap_or(Json::null()), "/action/context"))
  if body.contains("userMessage") {
    ignore(string_field(body, "userMessage", "/action"))
  }
  {
    wire: copy_json(value),
    name: string_field(body, "name", "/action"),
    surface_id: string_field(body, "surfaceId", "/action"),
    source_component_id: string_field(body, "sourceComponentId", "/action"),
    timestamp: string_field(body, "timestamp", "/action"),
  }
}

///|
pub fn Action::parse(text : String) -> Action raise {
  Action::from_json(
    @json.parse(
      text,
      max_nesting_depth=64,
      reject_duplicate_keys=true,
      preserve_number_repr=true,
    ),
  )
}

///|
pub fn Action::to_json(self : Action) -> Json {
  copy_json(self.wire)
}

///|
pub fn Action::context(self : Action) -> Json {
  match self.wire {
    { "action": { "context": context, .. }, .. } => copy_json(context)
    _ => abort("validated action")
  }
}