///|
fn CatalogRegistry::component_definition(
  self : CatalogRegistry,
  component : Json,
  default_catalog : Json,
) -> (Catalog, Json) raise ProtocolError {
  let fields = object(component, "/component")
  let id = if fields.get("@catalogId") is Some(String(id)) {
    id
  } else if default_catalog is String(id) {
    id
  } else {
    raise Invalid(path="/@catalogId", reason="component requires a catalog")
  }
  let catalog = self.get(id)
  let kind = string_field(fields, "component", "/component")
  guard catalog.definition is { "components": Object(definitions), .. } &&
    definitions.get(kind) is Some(definition) else {
    raise Invalid(path="/component", reason="unknown component")
  }
  (catalog, definition)
}

///|
fn schema_pointer(root : Json, reference : String) -> Json? {
  guard reference.has_prefix("#/") else { return None }
  let parts = pointer_parts(reference[1:].to_owned()) catch { _ => return None }
  lookup_parts(root, parts)
}

///|
fn lookup_parts(root : Json, parts : ArrayView[String]) -> Json? {
  if parts.is_empty() {
    return Some(root)
  }
  let child = match root {
    Object(fields) => fields.get(parts[0])
    Array(items) => {
      let index = @string.parse_int(parts[0]) catch { _ => return None }
      if index < 0 || index.to_string() != parts[0] {
        None
      } else {
        items.get(index)
      }
    }
    _ => None
  }
  match child {
    Some(value) => lookup_parts(value, parts[1:])
    None => None
  }
}

///|
fn component_refs(
  schema : Json,
  value : Json,
  catalog : Json,
  depth : Int32,
) -> Array[String] raise ProtocolError {
  guard depth < 128 else { raise StateError("schema reference depth exceeded") }
  let refs = []
  if schema is { "$ref": String(reference), .. } {
    if reference.has_suffix("#/$defs/ComponentId") ||
      reference.has_suffix("#/$defs/Child") {
      if value is String(id) {
        refs.push(id)
      }
      return refs
    }
    if reference.has_suffix("#/$defs/ChildList") {
      match value {
        Array(items) =>
          for item in items {
            if item is String(id) {
              refs.push(id)
            }
          }
        { "componentId": String(id), .. } => refs.push(id)
        _ => ()
      }
      return refs
    }
    if schema_pointer(catalog, reference) is Some(target) {
      refs.append(component_refs(target, value, catalog, depth + 1))
    }
  }
  if schema is { "properties": Object(properties), .. } &&
    value is Object(fields) {
    for key, item_schema in properties {
      if fields.get(key) is Some(item) {
        refs.append(component_refs(item_schema, item, catalog, depth + 1))
      }
    }
  }
  if schema is { "items": item_schema, .. } && value is Array(items) {
    for item in items {
      refs.append(component_refs(item_schema, item, catalog, depth + 1))
    }
  }
  for key in ["allOf", "anyOf", "oneOf"] {
    if schema is Object(fields) && fields.get(key) is Some(Array(branches)) {
      for branch in branches {
        refs.append(component_refs(branch, value, catalog, depth + 1))
      }
    }
  }
  refs
}

///|
fn composition(
  definition : Json,
  key : String,
  kind : String,
) -> Unit raise ProtocolError {
  if definition is Object(fields) {
    if fields.get(key) is Some(Array(allowed)) &&
      !allowed.contains(Json::string(kind)) {
      raise Invalid(
        path="/" + key,
        reason="composition does not permit " + kind,
      )
    }
    if fields.get("allOf") is Some(Array(branches)) {
      for branch in branches {
        composition(branch, key, kind)
      }
    }
  }
}

///|
fn visit_graph(
  id : String,
  edges : Map[String, Array[String]],
  marks : Map[String, Int32],
  depth : Int32,
) -> Unit raise ProtocolError {
  guard depth < 128 else { raise StateError("component graph depth exceeded") }
  match marks.get(id) {
    Some(1) => raise StateError("component reference cycle at " + id)
    Some(2) => return
    _ => ()
  }
  marks[id] = 1
  if edges.get(id) is Some(children) {
    for child in children {
      if edges.contains(child) {
        visit_graph(child, edges, marks, depth + 1)
      }
    }
  }
  marks[id] = 2
}

///|
fn CatalogRegistry::check_graph(
  self : CatalogRegistry,
  components : Map[String, Json],
  default_catalog : Json,
  complete~ : Bool,
) -> Unit raise ProtocolError {
  if complete && !components.contains("root") {
    raise StateError("surface has no root component")
  }
  let edges = Map([])
  for id, component in components {
    let (catalog, definition) = self.component_definition(
      component, default_catalog,
    )
    if id == "root" {
      composition(definition, "allowedParents", "Surface")
    }
    let refs = component_refs(definition, component, catalog.definition, 0)
    for child in refs {
      if components.get(child) is Some(child_component) {
        let (_, child_definition) = self.component_definition(
          child_component, default_catalog,
        )
        let parent_kind = string_field(object(component, ""), "component", "")
        let child_kind = string_field(
          object(child_component, ""),
          "component",
          "",
        )
        composition(definition, "allowedChildren", child_kind)
        composition(child_definition, "allowedParents", parent_kind)
      } else if complete {
        raise StateError("unresolved child: " + child)
      }
    }
    edges[id] = refs
  }
  let marks = Map([])
  for id, _ in components {
    visit_graph(id, edges, marks, 0)
  }
}

///|
pub fn SurfaceStore::validate_complete(
  self : SurfaceStore,
  surface_id : String,
) -> Unit raise ProtocolError {
  guard self.surfaces.get(surface_id) is Some(surface) else {
    raise StateError("unknown surface: " + surface_id)
  }
  self
  .registry()
  .check_graph(surface.components, surface.catalog_id, complete=true)
}

///|
pub fn SurfaceStore::data_at(
  self : SurfaceStore,
  surface_id : String,
  path : String,
) -> Json? raise ProtocolError {
  guard self.surfaces.get(surface_id) is Some(surface) else {
    raise StateError("unknown surface: " + surface_id)
  }
  lookup_parts(surface.data, pointer_parts(path)).map(copy_json)
}

///|
/// Carries only the requesting surface's opted-in data in transport metadata.
pub fn SurfaceStore::renderer_data_model(
  self : SurfaceStore,
  surface_id : String,
) -> Json? raise ProtocolError {
  guard self.surfaces.get(surface_id) is Some(surface) else {
    raise StateError("unknown surface: " + surface_id)
  }
  if !surface.send_data_model {
    return None
  }
  ignore(object(surface.data, "/surfaces/" + surface_id))
  Some({
    "version": "1.0",
    "surfaces": Json::object(Map([(surface_id, copy_json(surface.data))])),
  })
}