///|
priv struct Surface {
  mut data : Json
  mut components : Map[String, Json]
  catalog_id : Json
  send_data_model : Bool
  mut metadata : Json
}

///|
/// Stores independent surface states without I/O or renderer dependencies.
pub struct SurfaceStore {
  priv surfaces : Map[String, Surface]
  priv mut catalogs : CatalogRegistry?
  priv metadata_listeners : Map[Int32, (MetadataChange) -> Unit]
  priv mut next_listener : Int32
}

///|
pub fn SurfaceStore::new(catalogs? : CatalogRegistry) -> SurfaceStore {
  {
    surfaces: Map([]),
    catalogs,
    metadata_listeners: Map([]),
    next_listener: 0,
  }
}

///|
fn SurfaceStore::registry(
  self : SurfaceStore,
) -> CatalogRegistry raise ProtocolError {
  if self.catalogs is Some(catalogs) {
    return catalogs
  }
  let catalogs = CatalogRegistry::basic()
  self.catalogs = Some(catalogs)
  catalogs
}

///|
fn pointer_parts(path : String) -> Array[String] raise ProtocolError {
  if path == "/" || path == "" {
    return []
  }
  guard path.has_prefix("/") else {
    raise Invalid(path~, reason="expected absolute JSON pointer")
  }
  let parts = path[1:].split("/").map(part => part.to_owned()).collect()
  for part in parts {
    let mut i = 0
    while i < part.length() {
      if part[i] == '~' {
        guard i + 1 < part.length() &&
          (part[i + 1] == '0' || part[i + 1] == '1') else {
          raise Invalid(path~, reason="invalid JSON pointer escape")
        }
        i += 2
      } else {
        i += 1
      }
    }
  }
  guard parts.length() <= 100 else {
    raise Invalid(path~, reason="path depth exceeds 100")
  }
  parts.map(part => {
    let decoded = part
      .split("~1")
      .map(s => s.to_owned())
      .collect()
      .join("/")
      .split("~0")
      .map(s => s.to_owned())
      .collect()
      .join("~")
    guard !["__proto__", "constructor", "prototype"].contains(decoded) else {
      raise Invalid(path~, reason="forbidden path segment")
    }
    decoded
  })
}

///|
fn array_index(key : String) -> Int32 raise ProtocolError {
  let index = @string.parse_int(key) catch {
    _ => raise Invalid(path=key, reason="invalid array index")
  }
  guard index >= 0 && index.to_string() == key && index <= 10000 else {
    raise Invalid(path=key, reason="array index out of range")
  }
  index
}

///|
fn replace_at(
  node : Json,
  parts : ArrayView[String],
  value : Json,
) -> Json raise ProtocolError {
  if parts.is_empty() {
    return copy_json(value)
  }
  let key = parts[0]
  let rest = parts[1:]
  match node {
    Object(fields) => {
      if value == Json::null() && !fields.contains(key) {
        return node
      }
      let next = fields.copy()
      if rest.is_empty() && value == Json::null() {
        next.remove(key)
      } else {
        next[key] = replace_at(
          fields.get(key).unwrap_or(Json::null()),
          rest,
          value,
        )
      }
      Json::object(next)
    }
    Array(items) => {
      let index = array_index(key)
      if value == Json::null() && index >= items.length() {
        return node
      }
      let next = items.copy()
      while next.length() <= index {
        next.push(Json::null())
      }
      next[index] = replace_at(next[index], rest, value)
      Json::array(next)
    }
    Null =>
      if value == Json::null() {
        node
      } else {
        let numeric = !key.is_empty() &&
          key.iter().all(c => c.is_ascii_digit()) &&
          (key == "0" || !key.has_prefix("0"))
        replace_at(
          if numeric {
            Json::array([])
          } else {
            Json::empty_object()
          },
          parts,
          value,
        )
      }
    _ =>
      if value == Json::null() {
        node
      } else {
        raise Invalid(path=key, reason="cannot traverse a scalar")
      }
  }
}

///|
pub fn SurfaceStore::apply(
  self : SurfaceStore,
  message : Message,
) -> Unit raise ProtocolError {
  let body = object(object(message.wire, "")[message.operation], "")
  let id = message.target
  if message.operation == "createSurface" {
    guard !self.surfaces.contains(id) else {
      raise StateError("surface already exists: " + id)
    }
    let components : Map[String, Json] = Map([])
    if body.get("components") is Some(Array(items)) {
      for item in items {
        let component = Component::from_json(item)
        let default_catalog = if body.get("catalogId") is Some(String(id)) {
          id
        } else {
          ""
        }
        self
        .registry()
        .validate_component(component, catalog_id=default_catalog)
        components[string_field(object(item, ""), "id", "")] = copy_json(item)
      }
    }
    if !components.is_empty() {
      self
      .registry()
      .check_graph(
        components,
        body.get("catalogId").unwrap_or(Json::null()),
        complete=false,
      )
    }
    self.surfaces[id] = {
      data: copy_json(body.get("dataModel").unwrap_or(Json::empty_object())),
      components,
      catalog_id: body.get("catalogId").unwrap_or(Json::null()),
      send_data_model: body.get("sendDataModel") == Some(Json::boolean(true)),
      metadata: copy_json(body.get("metadata").unwrap_or(Json::empty_object())),
    }
    return
  }
  guard self.surfaces.get(id) is Some(surface) else {
    raise StateError("unknown surface: " + id)
  }
  match message.operation {
    "updateComponents" => {
      guard body["components"] is Array(items) else {
        abort("validated components")
      }
      let next = surface.components.copy()
      let default_catalog = if surface.catalog_id is String(id) {
        id
      } else {
        ""
      }
      for item in items {
        self
        .registry()
        .validate_component(
          Component::from_json(item),
          catalog_id=default_catalog,
        )
        next[string_field(object(item, ""), "id", "")] = copy_json(item)
      }
      self.registry().check_graph(next, surface.catalog_id, complete=false)
      let previous = surface.components
      surface.components = next
      for component_id, component in next {
        self.metadata_changed(
          id,
          Some(component_id),
          component_metadata(
            previous.get(component_id).unwrap_or(Json::empty_object()),
          ),
          component_metadata(component),
        )
      }
    }
    "updateDataModel" => {
      let path = if body.get("path") is Some(String(path)) { path } else { "/" }
      let parts = pointer_parts(path)
      let next = if parts.is_empty() && body["value"] == Json::null() {
        Json::empty_object()
      } else {
        replace_at(surface.data, parts, body["value"])
      }
      surface.data = next
    }
    "deleteSurface" => self.surfaces.remove(id)
    _ => abort("validated state message")
  }
}

///|
/// Returns an owned snapshot; changing it cannot mutate the store.
pub fn SurfaceStore::snapshot(
  self : SurfaceStore,
  surface_id : String,
) -> Json? {
  self.surfaces
  .get(surface_id)
  .map(s => {
    "surfaceId": Json::string(surface_id),
    "catalogId": s.catalog_id,
    "dataModel": copy_json(s.data),
    "metadata": copy_json(s.metadata),
    "sendDataModel": Json::boolean(s.send_data_model),
    "components": Json::array(s.components.values().map(copy_json).collect()),
  })
}