///|
/// Protocol failures include a JSON-pointer-like location in the input.
#derive(Debug)
pub(all) suberror ProtocolError {
  Invalid(path~ : String, reason~ : String)
  UnsupportedMessage(String)
  StateError(String)
  RuntimeError(code~ : String, reason~ : String)
  CallFailed(id~ : String, code~ : String, message~ : String)
}

///|
pub impl Show for ProtocolError with fn output(self, logger) {
  match self {
    Invalid(path~, reason~) => logger.write_string(path + ": " + reason)
    UnsupportedMessage(name) =>
      logger.write_string("Unsupported message: " + name)
    StateError(reason) => logger.write_string(reason)
    RuntimeError(code~, reason~) => logger.write_string(code + ": " + reason)
    CallFailed(id~, code~, message~) =>
      logger.write_string(id + " " + code + ": " + message)
  }
}

///|
/// A validated state-changing A2UI 1.0 envelope. Component properties remain
/// catalog-defined; envelope validation does not validate a component catalog.
pub struct Message {
  priv wire : Json
  priv operation : String
  priv target : String
}

///|
/// A component with a typed identity and catalog-owned JSON properties.
pub struct Component {
  priv wire : Json
}

///|
fn copy_json(value : Json) -> Json {
  match value {
    Object(fields) => Json::object(fields.map((_, v) => copy_json(v)))
    Array(values) => Json::array(values.map(copy_json))
    _ => value
  }
}

///|
fn object(value : Json, path : String) -> Map[String, Json] raise ProtocolError {
  guard value is Object(fields) else {
    raise Invalid(path~, reason="expected object")
  }
  fields
}

///|
fn string_field(
  fields : Map[String, Json],
  key : String,
  path : String,
) -> String raise ProtocolError {
  guard fields.get(key) is Some(String(value)) else {
    raise Invalid(path=path + "/" + key, reason="expected string")
  }
  value
}

///|
fn allowed_fields(
  fields : Map[String, Json],
  allowed : Array[String],
  path : String,
) -> Unit raise ProtocolError {
  for key, _ in fields {
    guard allowed.contains(key) else {
      raise Invalid(path=path + "/" + key, reason="unknown field")
    }
  }
}

///|
pub fn Component::from_json(value : Json) -> Component raise ProtocolError {
  let fields = object(value, "/component")
  let id = string_field(fields, "id", "/component")
  guard identifier(id) else {
    raise Invalid(path="/component/id", reason="expected Unicode identifier")
  }
  let kind = string_field(fields, "component", "/component")
  guard kind != "Surface" else {
    raise Invalid(
      path="/component/component",
      reason="Surface is an implicit container",
    )
  }
  { wire: copy_json(value), }
}

///|
pub fn Component::new(
  id : String,
  kind : String,
  properties~ : Json,
) -> Component raise ProtocolError {
  let fields = object(copy_json(properties), "/component")
  guard !fields.contains("id") && !fields.contains("component") else {
    raise Invalid(
      path="/component",
      reason="identity must be passed as arguments",
    )
  }
  fields["id"] = Json::string(id)
  fields["component"] = Json::string(kind)
  Component::from_json(Json::object(fields))
}

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

///|
fn validate_components(value : Json, path : String) -> Unit raise ProtocolError {
  guard value is Array(items) && !items.is_empty() else {
    raise Invalid(path~, reason="expected nonempty component array")
  }
  for item in items {
    ignore(Component::from_json(item))
  }
}

///|
pub fn Message::from_json(value : Json) -> Message raise ProtocolError {
  check_schema(schemas().agent, value)
  decode_state_message(value)
}

///|
fn decode_state_message(value : Json) -> Message raise ProtocolError {
  let envelope = object(value, "")
  guard envelope.get("version") == Some(Json::string("1.0")) else {
    raise Invalid(path="/version", reason="expected A2UI 1.0")
  }
  guard envelope.length() == 2 else {
    raise Invalid(path="", reason="expected version and exactly one message")
  }
  let operation = envelope.keys().filter(key => key != "version").collect()[0]
  let body = object(envelope[operation], "/" + operation)
  let path = "/" + operation
  match operation {
    "createSurface" => {
      allowed_fields(
        body,
        [
          "surfaceId", "catalogId", "sendDataModel", "components", "dataModel", "metadata",
        ],
        path,
      )
      if body.contains("catalogId") {
        ignore(string_field(body, "catalogId", path))
      }
      if body.get("sendDataModel") is Some(v) {
        guard v is True || v is False else {
          raise Invalid(path=path + "/sendDataModel", reason="expected boolean")
        }
      }
      if body.get("components") is Some(v) {
        validate_components(v, path + "/components")
      }
      if body.get("dataModel") is Some(v) {
        ignore(object(v, path + "/dataModel"))
      }
      if body.get("metadata") is Some(v) {
        let metadata = object(v, path + "/metadata")
        allowed_fields(metadata, ["extensions"], path + "/metadata")
        if metadata.get("extensions") is Some(ext) {
          ignore(object(ext, path + "/metadata/extensions"))
        }
      }
    }
    "updateComponents" => {
      allowed_fields(body, ["surfaceId", "components"], path)
      validate_components(
        body.get("components").unwrap_or(Json::null()),
        path + "/components",
      )
    }
    "updateDataModel" => {
      allowed_fields(body, ["surfaceId", "path", "value"], path)
      guard body.contains("value") else {
        raise Invalid(path=path + "/value", reason="required field")
      }
      if body.contains("path") {
        ignore(pointer_parts(string_field(body, "path", path)))
      }
    }
    "deleteSurface" => allowed_fields(body, ["surfaceId"], path)
    _ => raise UnsupportedMessage(operation)
  }
  let target = string_field(body, "surfaceId", path)
  { wire: copy_json(value), operation, target, }
}

///|
/// Decode a single envelope, rejecting duplicate keys and excessive nesting.
pub fn Message::parse(text : String) -> Message raise {
  Message::from_json(
    @json.parse(
      text,
      max_nesting_depth=64,
      reject_duplicate_keys=true,
      preserve_number_repr=true,
    ),
  )
}

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

///|
pub fn Message::surface_id(self : Message) -> String {
  self.target
}

///|
pub fn Message::kind(self : Message) -> String {
  self.operation
}

///|
pub fn Message::create_surface(
  surface_id : String,
  catalog_id~ : String,
  components~ : Array[Component],
  data_model~ : Json,
) -> Message raise ProtocolError {
  Message::from_json({
    "version": "1.0",
    "createSurface": {
      "surfaceId": Json::string(surface_id),
      "catalogId": Json::string(catalog_id),
      "components": Json::array(components.map(c => c.to_json())),
      "dataModel": data_model,
    },
  })
}

///|
pub fn Message::update_components(
  surface_id : String,
  components : Array[Component],
) -> Message raise ProtocolError {
  Message::from_json({
    "version": "1.0",
    "updateComponents": {
      "surfaceId": Json::string(surface_id),
      "components": Json::array(components.map(c => c.to_json())),
    },
  })
}

///|
pub fn Message::update_data(
  surface_id : String,
  value : Json,
  path~ : String = "/",
) -> Message raise ProtocolError {
  Message::from_json({
    "version": "1.0",
    "updateDataModel": {
      "surfaceId": Json::string(surface_id),
      "path": Json::string(path),
      "value": value,
    },
  })
}

///|
pub fn Message::delete_surface(
  surface_id : String,
) -> Message raise ProtocolError {
  Message::from_json({
    "version": "1.0",
    "deleteSurface": { "surfaceId": Json::string(surface_id) },
  })
}