///|
fn component_shape(
  component : Json,
  path : String,
) -> (Map[String, Json], Array[Json]) raise ProtocolError {
  guard component is { "type": String("object"), .. } else {
    raise Invalid(path~, reason="component must declare object type")
  }
  let bodies = []
  if component is { "properties": _, .. } {
    bodies.push(component)
  }
  if component is { "allOf": Array(branches), .. } {
    for branch in branches {
      if branch is { "$ref": String("common_types.json#/$defs/Checkable"), .. } &&
        object(branch, path).length() == 1 {
        continue
      }
      guard branch is { "type": String("object"), "properties": _, .. } &&
        !(branch is { "allOf": _, .. }) else {
        raise Invalid(
          path~,
          reason="component composition must contain a flat body and property traits",
        )
      }
      bodies.push(branch)
    }
  }
  guard bodies.length() == 1 &&
    bodies[0] is { "properties": Object(properties), .. } else {
    raise Invalid(path~, reason="component requires exactly one property body")
  }
  let required = if bodies[0] is { "required": Array(required), .. } {
    required
  } else {
    []
  }
  (properties, required)
}

///|
fn check_catalog_rules(catalog : Json) -> Unit raise ProtocolError {
  guard catalog is Object(fields) else {
    raise Invalid(path="/catalog", reason="expected object")
  }
  if fields.get("components") is Some(Object(components)) {
    for name, component in components {
      let (properties, _) = component_shape(component, "/components/" + name)
      guard properties.get("component")
        is Some({ "const": String(declared), .. }) &&
        declared == name else {
        raise Invalid(
          path="/components/" + name,
          reason="component discriminator must match its name",
        )
      }
    }
  }
  if fields.get("functions") is Some(Object(functions)) {
    for name, function in functions {
      guard identifier(name) else {
        raise Invalid(path="/functions/" + name, reason="invalid function name")
      }
      if function is { "allOf": _, .. } {
        raise Invalid(
          path="/functions/" + name,
          reason="function envelope composition belongs outside its declaration",
        )
      }
    }
  }
  walk_catalog_schema(catalog, "")
}

///|
fn walk_catalog_schema(
  value : Json,
  path : String,
  schema_map~ : Bool = false,
) -> Unit raise ProtocolError {
  let external = [
    "ComponentId", "Child", "ChildList", "DynamicString", "DynamicNumber", "DynamicBoolean",
    "DynamicStringList", "DynamicValue", "AccessibilityAttributes", "CheckRule",
    "Checkable", "Action", "DataBinding", "FunctionCall",
  ]
  match value {
    Object(fields) =>
      for key, item in fields {
        if schema_map {
          walk_catalog_schema(item, path + "/" + key)
          continue
        }
        if ["metadata", "examples", "const", "default", "enum", "description"].contains(
            key,
          ) {
          continue
        }
        if key == "$ref" || key == "$dynamicRef" {
          guard item is String(reference) else {
            raise Invalid(
              path=path + "/" + key,
              reason="expected reference string",
            )
          }
          let valid = if reference.has_prefix("#/$defs/") {
            reference != "#/$defs/anyComponent" &&
            reference != "#/$defs/anyFunction"
          } else if reference.has_prefix("#/components/") {
            path.has_prefix("/$defs/anyComponent")
          } else if reference.has_prefix("#/functions/") {
            path.has_prefix("/$defs/anyFunction")
          } else if reference.has_prefix("common_types.json#/$defs/") {
            external.contains(
              reference["common_types.json#/$defs/".length():].to_owned(),
            )
          } else {
            false
          }
          guard valid else {
            raise Invalid(
              path=path + "/" + key,
              reason="catalog reference target is not allowed: " + reference,
            )
          }
        }
        if key == "properties" && item is Object(properties) {
          for name, _ in properties {
            guard identifier(name) || name == "@call" || name == "@path" else {
              raise Invalid(
                path=path + "/properties/" + name,
                reason="invalid property or argument name",
              )
            }
          }
        }
        walk_catalog_schema(
          item,
          path + "/" + key,
          schema_map=[
            "properties", "patternProperties", "$defs", "dependentSchemas", "components",
            "functions",
          ].contains(key),
        )
      }
    Array(items) =>
      for i, item in items {
        walk_catalog_schema(item, path + "/" + i.to_string())
      }
    _ => ()
  }
}